[{"data":1,"prerenderedAt":-1},["ShallowReactive",2],{"similar-patrick-kidger--torchtyping":3,"tool-patrick-kidger--torchtyping":64},[4,17,27,35,43,56],{"id":5,"name":6,"github_repo":7,"description_zh":8,"stars":9,"difficulty_score":10,"last_commit_at":11,"category_tags":12,"status":16},3808,"stable-diffusion-webui","AUTOMATIC1111\u002Fstable-diffusion-webui","stable-diffusion-webui 是一个基于 Gradio 构建的网页版操作界面，旨在让用户能够轻松地在本地运行和使用强大的 Stable Diffusion 图像生成模型。它解决了原始模型依赖命令行、操作门槛高且功能分散的痛点，将复杂的 AI 绘图流程整合进一个直观易用的图形化平台。\n\n无论是希望快速上手的普通创作者、需要精细控制画面细节的设计师，还是想要深入探索模型潜力的开发者与研究人员，都能从中获益。其核心亮点在于极高的功能丰富度：不仅支持文生图、图生图、局部重绘（Inpainting）和外绘（Outpainting）等基础模式，还独创了注意力机制调整、提示词矩阵、负向提示词以及“高清修复”等高级功能。此外，它内置了 GFPGAN 和 CodeFormer 等人脸修复工具，支持多种神经网络放大算法，并允许用户通过插件系统无限扩展能力。即使是显存有限的设备，stable-diffusion-webui 也提供了相应的优化选项，让高质量的 AI 艺术创作变得触手可及。",162132,3,"2026-04-05T11:01:52",[13,14,15],"开发框架","图像","Agent","ready",{"id":18,"name":19,"github_repo":20,"description_zh":21,"stars":22,"difficulty_score":23,"last_commit_at":24,"category_tags":25,"status":16},1381,"everything-claude-code","affaan-m\u002Feverything-claude-code","everything-claude-code 是一套专为 AI 编程助手（如 Claude Code、Codex、Cursor 等）打造的高性能优化系统。它不仅仅是一组配置文件，而是一个经过长期实战打磨的完整框架，旨在解决 AI 代理在实际开发中面临的效率低下、记忆丢失、安全隐患及缺乏持续学习能力等核心痛点。\n\n通过引入技能模块化、直觉增强、记忆持久化机制以及内置的安全扫描功能，everything-claude-code 能显著提升 AI 在复杂任务中的表现，帮助开发者构建更稳定、更智能的生产级 AI 代理。其独特的“研究优先”开发理念和针对 Token 消耗的优化策略，使得模型响应更快、成本更低，同时有效防御潜在的攻击向量。\n\n这套工具特别适合软件开发者、AI 研究人员以及希望深度定制 AI 工作流的技术团队使用。无论您是在构建大型代码库，还是需要 AI 协助进行安全审计与自动化测试，everything-claude-code 都能提供强大的底层支持。作为一个曾荣获 Anthropic 黑客大奖的开源项目，它融合了多语言支持与丰富的实战钩子（hooks），让 AI 真正成长为懂上",140436,2,"2026-04-05T23:32:43",[13,15,26],"语言模型",{"id":28,"name":29,"github_repo":30,"description_zh":31,"stars":32,"difficulty_score":23,"last_commit_at":33,"category_tags":34,"status":16},2271,"ComfyUI","Comfy-Org\u002FComfyUI","ComfyUI 是一款功能强大且高度模块化的视觉 AI 引擎，专为设计和执行复杂的 Stable Diffusion 图像生成流程而打造。它摒弃了传统的代码编写模式，采用直观的节点式流程图界面，让用户通过连接不同的功能模块即可构建个性化的生成管线。\n\n这一设计巧妙解决了高级 AI 绘图工作流配置复杂、灵活性不足的痛点。用户无需具备编程背景，也能自由组合模型、调整参数并实时预览效果，轻松实现从基础文生图到多步骤高清修复等各类复杂任务。ComfyUI 拥有极佳的兼容性，不仅支持 Windows、macOS 和 Linux 全平台，还广泛适配 NVIDIA、AMD、Intel 及苹果 Silicon 等多种硬件架构，并率先支持 SDXL、Flux、SD3 等前沿模型。\n\n无论是希望深入探索算法潜力的研究人员和开发者，还是追求极致创作自由度的设计师与资深 AI 绘画爱好者，ComfyUI 都能提供强大的支持。其独特的模块化架构允许社区不断扩展新功能，使其成为当前最灵活、生态最丰富的开源扩散模型工具之一，帮助用户将创意高效转化为现实。",107662,"2026-04-03T11:11:01",[13,14,15],{"id":36,"name":37,"github_repo":38,"description_zh":39,"stars":40,"difficulty_score":23,"last_commit_at":41,"category_tags":42,"status":16},3704,"NextChat","ChatGPTNextWeb\u002FNextChat","NextChat 是一款轻量且极速的 AI 助手，旨在为用户提供流畅、跨平台的大模型交互体验。它完美解决了用户在多设备间切换时难以保持对话连续性，以及面对众多 AI 模型不知如何统一管理的痛点。无论是日常办公、学习辅助还是创意激发，NextChat 都能让用户随时随地通过网页、iOS、Android、Windows、MacOS 或 Linux 端无缝接入智能服务。\n\n这款工具非常适合普通用户、学生、职场人士以及需要私有化部署的企业团队使用。对于开发者而言，它也提供了便捷的自托管方案，支持一键部署到 Vercel 或 Zeabur 等平台。\n\nNextChat 的核心亮点在于其广泛的模型兼容性，原生支持 Claude、DeepSeek、GPT-4 及 Gemini Pro 等主流大模型，让用户在一个界面即可自由切换不同 AI 能力。此外，它还率先支持 MCP（Model Context Protocol）协议，增强了上下文处理能力。针对企业用户，NextChat 提供专业版解决方案，具备品牌定制、细粒度权限控制、内部知识库整合及安全审计等功能，满足公司对数据隐私和个性化管理的高标准要求。",87618,"2026-04-05T07:20:52",[13,26],{"id":44,"name":45,"github_repo":46,"description_zh":47,"stars":48,"difficulty_score":23,"last_commit_at":49,"category_tags":50,"status":16},2268,"ML-For-Beginners","microsoft\u002FML-For-Beginners","ML-For-Beginners 是由微软推出的一套系统化机器学习入门课程，旨在帮助零基础用户轻松掌握经典机器学习知识。这套课程将学习路径规划为 12 周，包含 26 节精炼课程和 52 道配套测验，内容涵盖从基础概念到实际应用的完整流程，有效解决了初学者面对庞大知识体系时无从下手、缺乏结构化指导的痛点。\n\n无论是希望转型的开发者、需要补充算法背景的研究人员，还是对人工智能充满好奇的普通爱好者，都能从中受益。课程不仅提供了清晰的理论讲解，还强调动手实践，让用户在循序渐进中建立扎实的技能基础。其独特的亮点在于强大的多语言支持，通过自动化机制提供了包括简体中文在内的 50 多种语言版本，极大地降低了全球不同背景用户的学习门槛。此外，项目采用开源协作模式，社区活跃且内容持续更新，确保学习者能获取前沿且准确的技术资讯。如果你正寻找一条清晰、友好且专业的机器学习入门之路，ML-For-Beginners 将是理想的起点。",84991,"2026-04-05T10:45:23",[14,51,52,53,15,54,26,13,55],"数据工具","视频","插件","其他","音频",{"id":57,"name":58,"github_repo":59,"description_zh":60,"stars":61,"difficulty_score":10,"last_commit_at":62,"category_tags":63,"status":16},3128,"ragflow","infiniflow\u002Fragflow","RAGFlow 是一款领先的开源检索增强生成（RAG）引擎，旨在为大语言模型构建更精准、可靠的上下文层。它巧妙地将前沿的 RAG 技术与智能体（Agent）能力相结合，不仅支持从各类文档中高效提取知识，还能让模型基于这些知识进行逻辑推理和任务执行。\n\n在大模型应用中，幻觉问题和知识滞后是常见痛点。RAGFlow 通过深度解析复杂文档结构（如表格、图表及混合排版），显著提升了信息检索的准确度，从而有效减少模型“胡编乱造”的现象，确保回答既有据可依又具备时效性。其内置的智能体机制更进一步，使系统不仅能回答问题，还能自主规划步骤解决复杂问题。\n\n这款工具特别适合开发者、企业技术团队以及 AI 研究人员使用。无论是希望快速搭建私有知识库问答系统，还是致力于探索大模型在垂直领域落地的创新者，都能从中受益。RAGFlow 提供了可视化的工作流编排界面和灵活的 API 接口，既降低了非算法背景用户的上手门槛，也满足了专业开发者对系统深度定制的需求。作为基于 Apache 2.0 协议开源的项目，它正成为连接通用大模型与行业专有知识之间的重要桥梁。",77062,"2026-04-04T04:44:48",[15,14,13,26,54],{"id":65,"github_repo":66,"name":67,"description_en":68,"description_zh":69,"ai_summary_zh":70,"readme_en":71,"readme_zh":72,"quickstart_zh":73,"use_case_zh":74,"hero_image_url":75,"owner_login":76,"owner_name":77,"owner_avatar_url":78,"owner_bio":79,"owner_company":80,"owner_location":81,"owner_email":82,"owner_twitter":83,"owner_website":84,"owner_url":85,"languages":86,"stars":91,"forks":92,"last_commit_at":93,"license":94,"difficulty_score":23,"env_os":95,"env_gpu":96,"env_ram":96,"env_deps":97,"category_tags":103,"github_topics":104,"view_count":23,"oss_zip_url":82,"oss_zip_packed_at":82,"status":16,"created_at":111,"updated_at":112,"faqs":113,"releases":143},2742,"patrick-kidger\u002Ftorchtyping","torchtyping","Type annotations and dynamic checking for a tensor's shape, dtype, names, etc.","torchtyping 是一个专为 PyTorch 设计的辅助库，旨在为张量（Tensor）的形状、数据类型、布局及维度名称提供清晰的类型注解与动态检查能力。在深度学习开发中，开发者常需依靠注释或断言来追踪张量维度，这不仅繁琐且容易引发难以排查的形状不匹配错误。torchtyping 通过引入直观的语法，让函数签名直接表达“输入张量应具备何种维度”，从而将隐式的文档说明转化为显式的代码约束。\n\n该工具特别适合 PyTorch 开发者与算法研究人员使用，尤其是那些受困于复杂模型中张量形状调试的人群。其核心亮点在于支持与 `typeguard` 集成，能够在代码运行时自动验证张量是否符合预设的形状与类型规范，一旦检测到维度不一致即刻报错，有效将潜在 Bug 扼杀在萌芽状态。此外，它还支持灵活定义任意数量的批次维度、特定尺寸限制以及命名张量等高级特性。\n\n值得注意的是，虽然 torchtyping 功能强大，但其作者目前更推荐新项目使用升级版工具 jaxtyping，后者兼容静态类型检查器且同样支持 PyTorch。不过，对于已有项目或希望快速提升代码可读性与健壮性的团队，torchtypi","torchtyping 是一个专为 PyTorch 设计的辅助库，旨在为张量（Tensor）的形状、数据类型、布局及维度名称提供清晰的类型注解与动态检查能力。在深度学习开发中，开发者常需依靠注释或断言来追踪张量维度，这不仅繁琐且容易引发难以排查的形状不匹配错误。torchtyping 通过引入直观的语法，让函数签名直接表达“输入张量应具备何种维度”，从而将隐式的文档说明转化为显式的代码约束。\n\n该工具特别适合 PyTorch 开发者与算法研究人员使用，尤其是那些受困于复杂模型中张量形状调试的人群。其核心亮点在于支持与 `typeguard` 集成，能够在代码运行时自动验证张量是否符合预设的形状与类型规范，一旦检测到维度不一致即刻报错，有效将潜在 Bug 扼杀在萌芽状态。此外，它还支持灵活定义任意数量的批次维度、特定尺寸限制以及命名张量等高级特性。\n\n值得注意的是，虽然 torchtyping 功能强大，但其作者目前更推荐新项目使用升级版工具 jaxtyping，后者兼容静态类型检查器且同样支持 PyTorch。不过，对于已有项目或希望快速提升代码可读性与健壮性的团队，torchtyping 依然是一个轻量且实用的选择，既能作为严谨的文档工具，也能在测试阶段充当可靠的“守门员”。","# Please use jaxtyping instead\n\n*Welcome! For new projects I now **strongly** recommend using my newer [jaxtyping](https:\u002F\u002Fgithub.com\u002Fgoogle\u002Fjaxtyping) project instead. It supports PyTorch, doesn't actually depend on JAX, and unlike TorchTyping it is compatible with static type checkers. The 'jax' in the name is now historical!*\n\n\u003Cbr>\n\u003Cbr>\n\u003Cbr>\n\nThe original torchtyping README is as follows.\n\n---\n\n\u003Ch1 align='center'>torchtyping\u003C\u002Fh1>\n\u003Ch2 align='center'>Type annotations for a tensor's shape, dtype, names, ...\u003C\u002Fh2>\n\nTurn this:\n```python\ndef batch_outer_product(x: torch.Tensor, y: torch.Tensor) -> torch.Tensor:\n    # x has shape (batch, x_channels)\n    # y has shape (batch, y_channels)\n    # return has shape (batch, x_channels, y_channels)\n\n    return x.unsqueeze(-1) * y.unsqueeze(-2)\n```\ninto this:\n```python\ndef batch_outer_product(x:   TensorType[\"batch\", \"x_channels\"],\n                        y:   TensorType[\"batch\", \"y_channels\"]\n                        ) -> TensorType[\"batch\", \"x_channels\", \"y_channels\"]:\n\n    return x.unsqueeze(-1) * y.unsqueeze(-2)\n```\n**with programmatic checking that the shape (dtype, ...) specification is met.**\n\nBye-bye bugs! Say hello to enforced, clear documentation of your code.\n\nIf (like me) you find yourself littering your code with comments like `# x has shape (batch, hidden_state)` or statements like `assert x.shape == y.shape` , just to keep track of what shape everything is, **then this is for you.**\n\n---\n\n## Installation\n\n```bash\npip install torchtyping\n```\n\nRequires Python >=3.7 and PyTorch >=1.7.0.\n\nIf using [`typeguard`](https:\u002F\u002Fgithub.com\u002Fagronholm\u002Ftypeguard) then it must be a version \u003C3.0.0.\n\n## Usage\n\n`torchtyping` allows for type annotating:\n\n- **shape**: size, number of dimensions;\n- **dtype** (float, integer, etc.);\n- **layout** (dense, sparse);\n- **names** of dimensions as per [named tensors](https:\u002F\u002Fpytorch.org\u002Fdocs\u002Fstable\u002Fnamed_tensor.html);\n- **arbitrary number of batch dimensions** with `...`;\n- **...plus anything else you like**, as `torchtyping` is highly extensible.\n\nIf [`typeguard`](https:\u002F\u002Fgithub.com\u002Fagronholm\u002Ftypeguard) is (optionally) installed then **at runtime the types can be checked** to ensure that the tensors really are of the advertised shape, dtype, etc. \n\n```python\n# EXAMPLE\n\nfrom torch import rand\nfrom torchtyping import TensorType, patch_typeguard\nfrom typeguard import typechecked\n\npatch_typeguard()  # use before @typechecked\n\n@typechecked\ndef func(x: TensorType[\"batch\"],\n         y: TensorType[\"batch\"]) -> TensorType[\"batch\"]:\n    return x + y\n\nfunc(rand(3), rand(3))  # works\nfunc(rand(3), rand(1))\n# TypeError: Dimension 'batch' of inconsistent size. Got both 1 and 3.\n```\n\n`typeguard` also has an import hook that can be used to automatically test an entire module, without needing to manually add `@typeguard.typechecked` decorators.\n\nIf you're not using `typeguard` then `torchtyping.patch_typeguard()` can be omitted altogether, and `torchtyping` just used for documentation purposes. If you're not already using `typeguard` for your regular Python programming, then strongly consider using it. It's a great way to squash bugs. Both `typeguard` and `torchtyping` also integrate with `pytest`, so if you're concerned about any performance penalty then they can be enabled during tests only.\n\n## API\n\n```python\ntorchtyping.TensorType[shape, dtype, layout, details]\n```\n\nThe core of the library.\n\nEach of `shape`, `dtype`, `layout`, `details` are optional.\n\n- The `shape` argument can be any of:\n  - An `int`: the dimension must be of exactly this size. If it is `-1` then any size is allowed.\n  - A `str`: the size of the dimension passed at runtime will be bound to this name, and all tensors checked that the sizes are consistent.\n  - A `...`: An arbitrary number of dimensions of any sizes.\n  - A `str: int` pair (technically it's a slice), combining both `str` and `int` behaviour. (Just a `str` on its own is equivalent to `str: -1`.)\n  - A `str: str` pair, in which case the size of the dimension passed at runtime will be bound to _both_ names, and all dimensions with either name must have the same size. (Some people like to use this as a way to associate multiple names with a dimension, for extra documentation purposes.)\n  - A `str: ...` pair, in which case the multiple dimensions corresponding to `...` will be bound to the name specified by `str`, and again checked for consistency between arguments.\n  - `None`, which when used in conjunction with `is_named` below, indicates a dimension that must _not_ have a name in the sense of [named tensors](https:\u002F\u002Fpytorch.org\u002Fdocs\u002Fstable\u002Fnamed_tensor.html).\n  - A `None: int` pair, combining both `None` and `int` behaviour. (Just a `None` on its own is equivalent to `None: -1`.)\n  - A `None: str` pair, combining both `None` and `str` behaviour. (That is, it must not have a named dimension, but must be of a size consistent with other uses of the string.)\n  - A `typing.Any`: Any size is allowed for this dimension (equivalent to `-1`).\n  - Any tuple of the above. For example.`TensorType[\"batch\": ..., \"length\": 10, \"channels\", -1]`. If you just want to specify the number of dimensions then use for example `TensorType[-1, -1, -1]` for a three-dimensional tensor.\n- The `dtype` argument can be any of:\n  - `torch.float32`, `torch.float64` etc.\n  - `int`, `bool`, `float`, which are converted to their corresponding PyTorch types. `float` is specifically interpreted as `torch.get_default_dtype()`, which is usually `float32`.\n- The `layout` argument can be either `torch.strided` or `torch.sparse_coo`, for dense and sparse tensors respectively.\n- The `details` argument offers a way to pass an arbitrary number of additional flags that customise and extend `torchtyping`. Two flags are built-in by default. `torchtyping.is_named` causes the [names of tensor dimensions](https:\u002F\u002Fpytorch.org\u002Fdocs\u002Fstable\u002Fnamed_tensor.html) to be checked, and `torchtyping.is_float` can be used to check that arbitrary floating point types are passed in. (Rather than just a specific one as with e.g. `TensorType[torch.float32]`.) For discussion on how to customise `torchtyping` with your own `details`, see the [further documentation](https:\u002F\u002Fgithub.com\u002Fpatrick-kidger\u002Ftorchtyping\u002Fblob\u002Fmaster\u002FFURTHER-DOCUMENTATION.md#custom-extensions).\n- Check multiple things at once by just putting them all together inside a single `[]`. For example `TensorType[\"batch\": ..., \"length\", \"channels\", float, is_named]`.\n\n```python\ntorchtyping.patch_typeguard()\n```\n\n`torchtyping` integrates with `typeguard` to perform runtime type checking. `torchtyping.patch_typeguard()` should be called at the global level, and will patch `typeguard` to check `TensorType`s.\n\nThis function is safe to run multiple times. (It does nothing after the first run). \n\n- If using `@typeguard.typechecked`, then `torchtyping.patch_typeguard()` should be called any time before using `@typeguard.typechecked`. For example you could call it at the start of each file using `torchtyping`.\n- If using `typeguard.importhook.install_import_hook`, then `torchtyping.patch_typeguard()` should be called any time before defining the functions you want checked. For example you could call `torchtyping.patch_typeguard()` just once, at the same time as the `typeguard` import hook. (The order of the hook and the patch doesn't matter.)\n- If you're not using `typeguard` then `torchtyping.patch_typeguard()` can be omitted altogether, and `torchtyping` just used for documentation purposes.\n\n```bash\npytest --torchtyping-patch-typeguard\n```\n\n`torchtyping` offers a `pytest` plugin to automatically run `torchtyping.patch_typeguard()` before your tests. `pytest` will automatically discover the plugin, you just need to pass the `--torchtyping-patch-typeguard` flag to enable it. Packages can then be passed to `typeguard` as normal, either by using `@typeguard.typechecked`, `typeguard`'s import hook, or the `pytest` flag `--typeguard-packages=\"your_package_here\"`.\n\n## Further documentation\n\nSee the [further documentation](https:\u002F\u002Fgithub.com\u002Fpatrick-kidger\u002Ftorchtyping\u002Fblob\u002Fmaster\u002FFURTHER-DOCUMENTATION.md) for:\n\n- FAQ;\n  - Including `flake8` and `mypy` compatibility;\n- How to write custom extensions to `torchtyping`;\n- Resources and links to other libraries and materials on this topic;\n- More examples.\n","# 请改用 jaxtyping\n\n*欢迎！对于新项目，我现在**强烈**建议使用我更新的 [jaxtyping](https:\u002F\u002Fgithub.com\u002Fgoogle\u002Fjaxtyping) 项目。它支持 PyTorch，实际上并不依赖 JAX，而且与 TorchTyping 不同的是，它兼容静态类型检查器。名称中的“jax”现在只是历史遗留了！*\n\n\u003Cbr>\n\u003Cbr>\n\u003Cbr>\n\n原始的 torchtyping README 如下。\n\n---\n\n\u003Ch1 align='center'>torchtyping\u003C\u002Fh1>\n\u003Ch2 align='center'>为张量的形状、数据类型、命名维度等添加类型注解\u003C\u002Fh2>\n\n将这段代码：\n```python\ndef batch_outer_product(x: torch.Tensor, y: torch.Tensor) -> torch.Tensor:\n    # x 的形状是 (batch, x_channels)\n    # y 的形状是 (batch, y_channels)\n    # 返回值的形状是 (batch, x_channels, y_channels)\n\n    return x.unsqueeze(-1) * y.unsqueeze(-2)\n```\n改为：\n```python\ndef batch_outer_product(x:   TensorType[\"batch\", \"x_channels\"],\n                        y:   TensorType[\"batch\", \"y_channels\"]\n                        ) -> TensorType[\"batch\", \"x_channels\", \"y_channels\"]:\n\n    return x.unsqueeze(-1) * y.unsqueeze(-2)\n```\n**同时对形状（数据类型等）规范进行程序化检查。**\n\n告别 bug！迎接强制执行且清晰明了的代码文档。\n\n如果你（像我一样）经常在代码中写类似 `# x 的形状是 (batch, hidden_state)` 的注释，或者插入诸如 `assert x.shape == y.shape` 的语句，仅仅是为了跟踪各个张量的形状，**那么这个库就非常适合你。**\n\n---\n\n## 安装\n\n```bash\npip install torchtyping\n```\n\n需要 Python >=3.7 和 PyTorch >=1.7.0。\n\n如果使用 [`typeguard`](https:\u002F\u002Fgithub.com\u002Fagronholm\u002Ftypeguard)，则其版本必须低于 3.0.0。\n\n## 使用方法\n\n`torchtyping` 允许对以下内容进行类型注解：\n\n- **形状**：大小、维度数；\n- **数据类型**（浮点数、整数等）；\n- **布局**（稠密、稀疏）；\n- **命名维度**，基于 [命名张量](https:\u002F\u002Fpytorch.org\u002Fdocs\u002Fstable\u002Fnamed_tensor.html)；\n- **任意数量的批次维度**，通过 `...` 表示；\n- **以及任何其他你想要的内容**，因为 `torchtyping` 具有高度可扩展性。\n\n如果（可选地）安装了 [`typeguard`](https:\u002F\u002Fgithub.com\u002Fagronholm\u002Ftypeguard)，**则可以在运行时检查类型**，以确保张量确实符合声明的形状、数据类型等。\n\n```python\n# 示例\n\nfrom torch import rand\nfrom torchtyping import TensorType, patch_typeguard\nfrom typeguard import typechecked\n\npatch_typeguard()  # 在 @typechecked 之前调用\n\n@typechecked\ndef func(x: TensorType[\"batch\"],\n         y: TensorType[\"batch\"]) -> TensorType[\"batch\"]:\n    return x + y\n\nfunc(rand(3), rand(3))  # 正常运行\nfunc(rand(3), rand(1))\n# TypeError: 维度 'batch' 的大小不一致。分别得到 1 和 3。\n```\n\n`typeguard` 还提供了一个导入钩子，可以用来自动测试整个模块，而无需手动添加 `@typeguard.typechecked` 装饰器。\n\n如果你不使用 `typeguard`，则可以完全省略 `torchtyping.patch_typeguard()`，仅将 `torchtyping` 用于文档目的。如果你目前还没有在常规 Python 编程中使用 `typeguard`，强烈建议考虑使用它。这是一种很好的方式来消除 bug。此外，`typeguard` 和 `torchtyping` 都可以与 `pytest` 集成，因此如果你担心性能开销，也可以只在测试时启用它们。\n\n## API\n\n```python\ntorchtyping.TensorType[shape, dtype, layout, details]\n```\n\n该库的核心。\n\n`shape`、`dtype`、`layout`、`details` 各参数均可选。\n\n- `shape` 参数可以是以下任意一种：\n  - 一个 `int`：维度必须精确为该大小。若为 `-1`，则允许任意大小。\n  - 一个 `str`：运行时传入的维度大小将绑定到该名称，并且所有张量都会被检查以确保尺寸一致。\n  - 一个 `...`：表示任意数量、任意大小的维度。\n  - 一个 `str: int` 对（实际上是切片），结合了 `str` 和 `int` 的行为。（单独的 `str` 等价于 `str: -1`。）\n  - 一个 `str: str` 对，此时运行时传入的维度大小将同时绑定到这两个名称，且任何带有其中任一名称的维度都必须具有相同的大小。（有些人喜欢用这种方式为一个维度关联多个名称，以增强文档性。）\n  - 一个 `str: ...` 对，此时与 `...` 对应的多个维度将被绑定到 `str` 指定的名称，并再次检查各参数之间的一致性。\n  - `None`，当与下面的 `is_named` 一起使用时，表示该维度在 [命名张量](https:\u002F\u002Fpytorch.org\u002Fdocs\u002Fstable\u002Fnamed_tensor.html) 的意义上**不应**具有名称。\n  - 一个 `None: int` 对，结合了 `None` 和 `int` 的行为。（单独的 `None` 等价于 `None: -1`。）\n  - 一个 `None: str` 对，结合了 `None` 和 `str` 的行为。（即该维度不应具有命名，但其大小必须与其他使用该字符串的地方保持一致。）\n  - `typing.Any`：该维度允许任意大小（等同于 `-1`）。\n  - 上述类型的任意元组。例如：`TensorType[\"batch\": ..., \"length\": 10, \"channels\", -1]`。如果只想指定维度的数量，可以使用例如 `TensorType[-1, -1, -1]` 表示三维张量。\n- `dtype` 参数可以是以下任意一种：\n  - `torch.float32`、`torch.float64` 等。\n  - `int`、`bool`、`float`，这些会被转换为对应的 PyTorch 类型。`float` 特别地会被解释为 `torch.get_default_dtype()`，通常为 `float32`。\n- `layout` 参数可以是 `torch.strided` 或 `torch.sparse_coo`，分别用于稠密和稀疏张量。\n- `details` 参数提供了一种传递任意数量附加标志的方式，用于自定义和扩展 `torchtyping`。默认内置两个标志。`torchtyping.is_named` 会检查 [张量维度的名称](https:\u002F\u002Fpytorch.org\u002Fdocs\u002Fstable\u002Fnamed_tensor.html)，而 `torchtyping.is_float` 可用于检查是否传入了任意浮点类型。（而不是像 `TensorType[torch.float32]` 那样只检查特定类型。）有关如何使用自定义 `details` 来扩展 `torchtyping` 的讨论，请参阅[进一步的文档](https:\u002F\u002Fgithub.com\u002Fpatrick-kidger\u002Ftorchtyping\u002Fblob\u002Fmaster\u002FFURTHER-DOCUMENTATION.md#custom-extensions)。\n- 可以通过将多个条件组合在一个方括号内来同时检查多项内容。例如：`TensorType[\"batch\": ..., \"length\", \"channels\", float, is_named]`。\n\n```python\ntorchtyping.patch_typeguard()\n```\n\n`torchtyping` 与 `typeguard` 集成，以执行运行时类型检查。应在全局范围内调用 `torchtyping.patch_typeguard()`，它会修补 `typeguard` 以检查 `TensorType`。\n\n此函数可以多次安全调用。（首次调用后便不再执行任何操作。）\n\n- 如果使用 `@typeguard.typechecked`，则应在使用 `@typeguard.typechecked` 之前随时调用 `torchtyping.patch_typeguard()`。例如，可以在每个使用 `torchtyping` 的文件开头调用。\n- 如果使用 `typeguard.importhook.install_import_hook`，则应在定义要进行检查的函数之前随时调用 `torchtyping.patch_typeguard()`。例如，可以在安装 `typeguard` 导入钩子的同时仅调用一次 `torchtyping.patch_typeguard()`。（钩子和补丁的顺序并不重要。）\n- 如果不使用 `typeguard`，则可以完全省略 `torchtyping.patch_typeguard()`，仅将 `torchtyping` 用于文档目的。\n\n```bash\npytest --torchtyping-patch-typeguard\n```\n\n`torchtyping` 提供了一个 `pytest` 插件，可在测试前自动运行 `torchtyping.patch_typeguard()`。`pytest` 会自动发现该插件，您只需传递 `--torchtyping-patch-typeguard` 标志即可启用它。随后可以像往常一样将包传递给 `typeguard`，无论是通过 `@typeguard.typechecked`、`typeguard` 的导入钩子，还是通过 `pytest` 标志 `--typeguard-packages=\"your_package_here\"`。\n\n## 进一步的文档\n\n请参阅[进一步的文档](https:\u002F\u002Fgithub.com\u002Fpatrick-kidger\u002Ftorchtyping\u002Fblob\u002Fmaster\u002FFURTHER-DOCUMENTATION.md)，了解：\n\n- 常见问题解答；\n  - 包括与 `flake8` 和 `mypy` 的兼容性；\n- 如何编写 `torchtyping` 的自定义扩展；\n- 与此主题相关的其他库和资料的资源与链接；\n- 更多示例。","# torchtyping 快速上手指南\n\n> **⚠️ 重要提示**：原作者强烈建议新项目使用其更新的 **[jaxtyping](https:\u002F\u002Fgithub.com\u002Fgoogle\u002Fjaxtyping)** 库。它同样支持 PyTorch，不依赖 JAX，且兼容静态类型检查器（如 mypy）。本文档仅针对仍需使用 `torchtyping` 的旧项目。\n\n`torchtyping` 允许你为 PyTorch 张量的形状（shape）、数据类型（dtype）、布局及维度名称添加类型注解，并可在运行时进行自动检查，从而消除维度不匹配的 Bug，让代码文档更清晰。\n\n## 环境准备\n\n在开始之前，请确保满足以下系统要求：\n\n- **Python**: >= 3.7\n- **PyTorch**: >= 1.7.0\n- **可选依赖**: `typeguard` (版本需 \u003C 3.0.0)，用于启用运行时类型检查。\n\n## 安装步骤\n\n使用 pip 进行安装。国内用户推荐使用清华或阿里镜像源以加速下载。\n\n```bash\n# 使用默认源\npip install torchtyping\n\n# 或使用国内镜像源（推荐）\npip install torchtyping -i https:\u002F\u002Fpypi.tuna.tsinghua.edu.cn\u002Fsimple\n```\n\n若需启用运行时检查，请同时安装兼容版本的 `typeguard`：\n\n```bash\npip install \"typeguard\u003C3.0.0\"\n```\n\n## 基本使用\n\n### 1. 基础注解（仅文档用途）\n\n即使不安装 `typeguard`，你也可以直接使用 `TensorType` 来替代注释，明确表达张量的维度含义。\n\n```python\nimport torch\nfrom torchtyping import TensorType\n\ndef batch_outer_product(\n    x: TensorType[\"batch\", \"x_channels\"],\n    y: TensorType[\"batch\", \"y_channels\"]\n) -> TensorType[\"batch\", \"x_channels\", \"y_channels\"]:\n    # 代码逻辑保持不变\n    return x.unsqueeze(-1) * y.unsqueeze(-2)\n```\n\n### 2. 启用运行时检查\n\n若要程序在运行时自动验证张量形状是否符合注解，需配合 `typeguard` 使用。\n\n**步骤：**\n1. 导入并调用 `patch_typeguard()`（只需调用一次）。\n2. 使用 `@typechecked` 装饰器标记函数。\n\n```python\nfrom torch import rand\nfrom torchtyping import TensorType, patch_typeguard\nfrom typeguard import typechecked\n\n# 必须在使用 @typechecked 之前调用\npatch_typeguard()\n\n@typechecked\ndef add_tensors(\n    x: TensorType[\"batch\"],\n    y: TensorType[\"batch\"]\n) -> TensorType[\"batch\"]:\n    return x + y\n\n# 正常情况：形状一致，运行成功\nadd_tensors(rand(3), rand(3))\n\n# 异常情况：形状不一致，抛出 TypeError\n# add_tensors(rand(3), rand(1)) \n# 报错信息示例：TypeError: Dimension 'batch' of inconsistent size. Got both 1 and 3.\n```\n\n### 3. 高级用法简介\n\n`TensorType` 支持丰富的参数定义：\n\n- **固定尺寸**: 使用整数，如 `TensorType[10]`。\n- **任意尺寸**: 使用 `-1` 或 `typing.Any`。\n- **任意维度数量**: 使用 `...`，如 `TensorType[\"batch\": ..., \"channels\"]`。\n- **数据类型**: 指定 `float`, `int`, `torch.float32` 等。\n- **命名张量**: 结合 `is_named` 标志检查维度名称。\n\n示例：\n```python\n# 定义一个浮点型、至少两维（第一维为 batch，第二维固定为 10）的张量\ndef func(x: TensorType[\"batch\": ..., 10, float]) -> None:\n    pass\n```","某深度学习团队在开发多模态融合模型时，需要频繁处理来自视觉编码器和文本编码器的张量，确保它们在批次维度（batch）上严格对齐才能进行后续计算。\n\n### 没有 torchtyping 时\n- 开发者必须在函数内部编写大量 `assert x.shape[0] == y.shape[0]` 语句来手动验证维度一致性，代码冗余且易遗漏。\n- 关键张量的形状含义（如“时间步”或“特征通道”）仅靠注释 `# shape: (batch, time)` 说明，新成员阅读代码时极易误解。\n- 当输入数据因预处理失误导致维度不匹配时，错误往往在深层网络运算中才爆发，报错信息晦涩难懂，排查耗时。\n- 重构代码时缺乏自动约束，修改某个层的输出维度后，无法立即发现下游所有依赖该形状的函数已失效。\n\n### 使用 torchtyping 后\n- 通过 `TensorType[\"batch\", \"time\"]` 语法直接在类型注解中声明形状，torchtyping 配合 typeguard 在运行时自动拦截维度不匹配的调用并抛出清晰异常。\n- 函数签名即文档，`\"batch\"`、`\"channels\"` 等语义化标签让张量用途一目了然，彻底消除了维护过时注释的负担。\n- 错误在数据进入函数的第一时间被捕获，报错信息明确指出是哪个命名维度（如 'batch'）出现了大小冲突（如 32 vs 64），定位问题秒级完成。\n- 静态分析与动态检查双重保障，一旦调整上游张量结构，所有未适配的下游函数会立即报错，大幅降低重构风险。\n\ntorchtyping 将隐式的张量形状约定转化为显式的、可自动执行的代码契约，从根源上杜绝了深度学习中最常见的维度错位 Bug。","https:\u002F\u002Foss.gittoolsai.com\u002Fimages\u002Fpatrick-kidger_torchtyping_0a078fd7.png","patrick-kidger","Patrick Kidger","https:\u002F\u002Foss.gittoolsai.com\u002Favatars\u002Fpatrick-kidger_a5d56fa4.png","ML+proteins, sciML, numerics, neural ODEs ╱ building 'scipy w\u002F autodiff+GPU' in JAX: Equinox, Diffrax, Lineax, etc ╱ solo traveller, martial artist, scuba diver","Cradle.bio","Zürich",null,"PatrickKidger","https:\u002F\u002Fkidger.site","https:\u002F\u002Fgithub.com\u002Fpatrick-kidger",[87],{"name":88,"color":89,"percentage":90},"Python","#3572A5",100,1476,39,"2026-03-23T20:36:27","Apache-2.0","","未说明",{"notes":98,"python":99,"dependencies":100},"作者强烈建议新项目改用 jaxtyping，因为它支持静态类型检查器且不再依赖 JAX。若使用 typeguard 进行运行时检查，版本必须低于 3.0.0。若不安装 typeguard，该库仅作为文档注释使用。提供 pytest 插件以在测试时自动启用类型检查。",">=3.7",[101,102],"torch>=1.7.0","typeguard\u003C3.0.0 (可选)",[13],[105,106,107,108,109,110],"tensors","named-tensors","shape","pytorch","typing","python-typing","2026-03-27T02:49:30.150509","2026-04-06T09:45:04.868562",[114,119,124,129,134,139],{"id":115,"question_zh":116,"answer_zh":117,"source_url":118},12706,"为什么 VSCode、Pylance 或 Pyright 报错说 Tensor 与 TensorType 不兼容？","这是静态类型检查器（如 Pyright）的限制，它们目前无法正确理解带有自定义 `__class_getitem__` 的类（即 `TensorType[...]` 这种形式）。Pyright 看到自定义类型的 `[...]` 语法通常会直接放弃分析，而不是检查其返回值。\n\n解决方案：\n1. 目前主要建议在 torchtyping 的 README 中推荐使用运行时类型检查器，因为静态检查器存在此类局限。\n2. 可以尝试修改源码中相关行的返回注解为 `torch.Tensor`（见项目源码 tensor_type.py 第 81 行），如果有效可以提交 PR。\n3. 根本原因在于 Pyright 需要改进对 `__class_getitem__` 的支持，这属于上游工具的问题。","https:\u002F\u002Fgithub.com\u002Fpatrick-kidger\u002Ftorchtyping\u002Fissues\u002F26",{"id":120,"question_zh":121,"answer_zh":122,"source_url":123},12707,"torchtyping 支持 Python 3.7 吗？","支持。该问题已通过相关更新解决。\n\n维护者指出，不太可能支持低于 Python 3.7 的版本，原因如下：\n1. PyTorch 很快也将停止支持低于 3.7 的版本。\n2. 支持更低版本需要额外工作，因为 `__class_getitem__` 特性是 Python 3.7+ 才引入的。","https:\u002F\u002Fgithub.com\u002Fpatrick-kidger\u002Ftorchtyping\u002Fissues\u002F7",{"id":125,"question_zh":126,"answer_zh":127,"source_url":128},12708,"使用最新版 PyTorch 时遇到 'Cannot subclass _TensorBase directly' 错误怎么办？","这是因为新版 PyTorch 禁止直接子类化底层的 C++ `_TensorBase` 类型，强制要求直接子类化 `torch.Tensor`。\n\n原因：torchtyping 内部创建 mixin 类的机制导致元类型认为正在创建一个不以 `torch.Tensor` 为基类的新类，从而触发错误。\n\n解决方案：该问题已在后续版本中修复。确保升级 torchtyping 到最新版本即可。对于 PyTorch 夜间版（nightlies）可能需要更仔细的检查，但稳定版（torch \u003C 2.4 及后续修复版）应能正常工作。","https:\u002F\u002Fgithub.com\u002Fpatrick-kidger\u002Ftorchtyping\u002Fissues\u002F48",{"id":130,"question_zh":131,"answer_zh":132,"source_url":133},12709,"是否支持命名维度共享未指定的尺寸（例如多个维度大小相同但名称不同）？","社区曾提出此需求（例如让名为 \"token\", \"predicate\" 的维度共享一个名为 \"words\" 的尺寸）。\n\n目前的讨论倾向是保持简单：建议使用 `str: str` 的语法，让两个名字都绑定，并根据这两个名字进行检查，而不引入额外的 `sizeof` 符号或复杂的“确保名字在其他地方被使用”的检查逻辑。这有助于提升新用户的体验。如果你需要此功能，可以参考相关讨论尝试提交 PR。","https:\u002F\u002Fgithub.com\u002Fpatrick-kidger\u002Ftorchtyping\u002Fissues\u002F15",{"id":135,"question_zh":136,"answer_zh":137,"source_url":138},12710,"torchtyping 是否计划支持 torch.Distribution 类型注解？","目前暂无计划支持。维护者认为这可能引发复杂性问题（例如与 `typing.Generic` 的用例冲突）。\n\n此外，torchtyping 目前已进入维护模式，开发重点已转向 [jaxtyping](https:\u002F\u002Fgithub.com\u002Fpatrick-kidger\u002Fjaxtyping)。建议有类似需求的用户关注或试用 jaxtyping。","https:\u002F\u002Fgithub.com\u002Fpatrick-kidger\u002Ftorchtyping\u002Fissues\u002F44",{"id":140,"question_zh":141,"answer_zh":142,"source_url":133},12711,"如何在 mypy 中安全地使用带有切片或特定尺寸标注的 TensorType（如 TensorType[batch: ..., 10]）？","目前这在 mypy 中尚不可用，主要受限于 mypy 自身的问题（参考 GitHub issue: python\u002Fmypy#10266）。在该 mypy 问题解决之前，涉及切片 `...` 或具体尺寸（如 `TensorType[\"row\": 10, \"col\": 10]`）的高级注解可能无法被 mypy 正确识别。建议暂时避免在强依赖 mypy 的场景中使用这些高级特性，或关注 mypy 的更新进度。",[]]