# nexus **Repository Path**: Ivanmax/nexus ## Basic Information - **Project Name**: nexus - **Description**: 一个用于通用控制流的深度学习框架 - **Primary Language**: Unknown - **License**: Not specified - **Default Branch**: master - **Homepage**: None - **GVP Project**: No ## Statistics - **Stars**: 0 - **Forks**: 1 - **Created**: 2026-03-18 - **Last Updated**: 2026-03-18 ## Categories & Tags **Categories**: Uncategorized **Tags**: None ## README # Nexus: 支持控制流的深度学习中间表示 Nexus 是一个为深度学习模型设计的中间表示(IR),原生支持控制流(如 `if`、`loop`、`break`、`continue`)。它可以从 PyTorch 的 TorchScript 图转换而来,并提供了一个轻量级的解释器用于执行 IR 图,便于调试、分析和验证。 ## 特性 - **完整的控制流支持**:能够表示条件分支、循环(包括嵌套)以及 `break`/`continue`。 - **TorchScript 导入**:提供 `import_torchscript` 函数,将 `torch.jit.ScriptModule` 转换为 Nexus IR 图。 - **IR 解释器**:内置解释器可逐块执行 IR 图,并打印详细的执行日志(支持 `logging.DEBUG` 级别)。 - **可视化**:可将 IR 图导出为 Graphviz DOT 格式,便于使用 `dot` 命令生成图片。 - **验证与序列化**:提供 IR 图验证工具和 JSON 序列化/反序列化功能。 ## 安装 克隆仓库后,使用 `pip` 安装: ```bash git clone https://github.com/yourusername/nexus.git cd nexus pip install -e . ``` 如需运行示例,请确保安装了 PyTorch: ```bash pip install torch ``` ## 快速开始 ### 从 TorchScript 转换并执行 ```python import torch from nexus.converter import import_torchscript from nexus.interpreter import execute_irg @torch.jit.script def cond_example(x: torch.Tensor, flag: bool) -> torch.Tensor: if flag: return x + 1 else: return x * 2 graph = import_torchscript(cond_example) result = execute_irg(graph, {'x': torch.tensor(5.0), 'flag': True}) print(result) # 输出 6.0 ``` ### 可视化 IR 图 ```python from nexus.ir import to_dot dot_str = to_dot(graph) with open('graph.dot', 'w') as f: f.write(dot_str) # 然后使用 Graphviz 生成图片: dot -Tpng graph.dot -o graph.png ``` ### 手动构建 IR 图 您也可以通过 API 手动构建 IR 图,例如: ```python from nexus.ir import IRGraph, BasicBlock, Node, NodeKind, Value graph = IRGraph('my_graph') entry = BasicBlock('entry') # ... 添加节点和边 ... graph.entry_block = entry ``` ## 项目结构 ``` nexus/ ├── __init__.py ├── __main__.py ├── converter/ # TorchScript 转换器 ├── interpreter/ # IR 解释器 ├── ir/ # IR 核心定义、构建器、序列化、可视化、验证 ├── examples/ # 各种示例脚本 └── tests/ # 单元测试 ``` ## 运行示例 在项目根目录执行以下命令运行示例: ```bash python -m nexus.examples.example_cond python -m nexus.examples.example_while python -m nexus.examples.example_nested_if python -m nexus.examples.example_simple_nested python -m nexus.examples.example_break_continue python -m nexus.examples.example_complex ``` 每个示例都会打印 TorchScript 原始结果与 Nexus 执行结果,并生成对应的 `.dot` 文件。 ## 日志 Nexus 使用 Python 的 `logging` 模块输出详细日志。可通过以下方式启用: ```python import logging logging.basicConfig(level=logging.DEBUG) ``` ## 贡献 欢迎提交 Issue 和 Pull Request。在开发时,请确保通过单元测试: ```bash pytest nexus/tests/ ``` ## 许可证 MIT ``` 此 README 包含了项目简介、特性、安装、快速上手示例、项目结构、运行方式、日志说明和贡献指南,基本覆盖了用户可能关心的内容。如果需要补充特定细节(如对 `break`/`continue` 的支持程度),可以再行修改。