[{"data":1,"prerenderedAt":-1},["ShallowReactive",2],{"similar-ankane--torch.rb":3,"tool-ankane--torch.rb":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":69,"readme_en":70,"readme_zh":71,"quickstart_zh":72,"use_case_zh":73,"hero_image_url":74,"owner_login":75,"owner_name":76,"owner_avatar_url":77,"owner_bio":78,"owner_company":78,"owner_location":79,"owner_email":80,"owner_twitter":78,"owner_website":81,"owner_url":82,"languages":83,"stars":92,"forks":93,"last_commit_at":94,"license":95,"difficulty_score":96,"env_os":97,"env_gpu":98,"env_ram":99,"env_deps":100,"category_tags":106,"github_topics":78,"view_count":23,"oss_zip_url":78,"oss_zip_packed_at":78,"status":16,"created_at":107,"updated_at":108,"faqs":109,"releases":138},3335,"ankane\u002Ftorch.rb","torch.rb","Deep learning for Ruby, powered by LibTorch","torch.rb 是一款让 Ruby 开发者也能轻松涉足深度学习领域的开源工具。它基于强大的 LibTorch（PyTorch 的 C++ 后端），将 PyTorch 的核心功能无缝引入 Ruby 生态，解决了以往 Ruby 社区缺乏原生、高性能深度学习框架的痛点。\n\n对于熟悉 Ruby 语法但希望利用其优雅特性进行模型开发、原型验证或教学演示的开发者与研究人员来说，torch.rb 是理想选择。它无需切换至 Python 环境，即可在现有的 Ruby 应用中直接构建和训练神经网络。\n\n该工具的独特亮点在于完美保留了 Ruby 的编程习惯：它将 PyTorch 中就地修改的方法后缀从下划线改为感叹号（如 `add!`），将布尔判断方法前缀从 `is_` 改为问号（如 `tensor?`），并使用 Numo 替代 NumPy 进行数据交互。此外，它还拥有完善的生态系统，提供针对计算机视觉、自然语言处理、音频分析及推荐系统等任务的专用扩展库。无论是进行图像分类、序列建模还是生成对抗网络实验，torch.rb 都能让你用熟悉的 Ruby 代码高效完成，极大地降低了深度学习的技术门槛。","# Torch.rb\n\n:fire: Deep learning for Ruby, powered by [LibTorch](https:\u002F\u002Fpytorch.org)\n\nAlso check out:\n\n- [TorchVision](https:\u002F\u002Fgithub.com\u002Fankane\u002Ftorchvision-ruby) for computer vision tasks\n- [TorchText](https:\u002F\u002Fgithub.com\u002Fankane\u002Ftorchtext-ruby) for text and NLP tasks\n- [TorchAudio](https:\u002F\u002Fgithub.com\u002Fankane\u002Ftorchaudio-ruby) for audio tasks\n- [TorchCodec](https:\u002F\u002Fgithub.com\u002Fankane\u002Ftorchcodec-ruby) for audio and video encoding\n- [TorchRec](https:\u002F\u002Fgithub.com\u002Fankane\u002Ftorchrec-ruby) for recommendation systems\n- [TorchData](https:\u002F\u002Fgithub.com\u002Fankane\u002Ftorchdata-ruby) for data loading\n\nAs well as:\n\n- [Transformers](https:\u002F\u002Fgithub.com\u002Fankane\u002Ftransformers-ruby) for transformers\n- [Safetensors](https:\u002F\u002Fgithub.com\u002Fankane\u002Fsafetensors-ruby) for storing tensors\n\n[![Build Status](https:\u002F\u002Fgithub.com\u002Fankane\u002Ftorch.rb\u002Factions\u002Fworkflows\u002Fbuild.yml\u002Fbadge.svg)](https:\u002F\u002Fgithub.com\u002Fankane\u002Ftorch.rb\u002Factions)\n\n## Installation\n\nFirst, [download LibTorch](https:\u002F\u002Fpytorch.org\u002Fget-started\u002Flocally\u002F). For Mac arm64, use:\n\n```sh\ncurl -L https:\u002F\u002Fdownload.pytorch.org\u002Flibtorch\u002Fcpu\u002Flibtorch-macos-arm64-2.10.0.zip > libtorch.zip\nunzip -q libtorch.zip\n```\n\nFor Linux x86-64, use the build that matches your CUDA version. For other platforms, build LibTorch from source.\n\nThen run:\n\n```sh\nbundle config set build.torch-rb --with-torch-dir=\u002Fpath\u002Fto\u002Flibtorch\n```\n\nAnd add this line to your application’s Gemfile:\n\n```ruby\ngem \"torch-rb\"\n```\n\nIt can take 5-10 minutes to compile the extension. Windows is not currently supported.\n\n## Getting Started\n\nA good place to start is [Deep Learning with Torch.rb: A 60 Minute Blitz](tutorials\u002Fblitz\u002FREADME.md).\n\n## Tutorials\n\n- [Transfer learning](tutorials\u002Ftransfer_learning\u002FREADME.md)\n- [Sequence models](tutorials\u002Fnlp\u002Fsequence_models.md)\n- [Word embeddings](tutorials\u002Fnlp\u002Fword_embeddings.md)\n\n## Examples\n\n- [Image classification with MNIST](examples\u002Fmnist) ([日本語版](https:\u002F\u002Fqiita.com\u002Fkojix2\u002Fitems\u002Fc19c36dc1bf73ea93409))\n- [Collaborative filtering with MovieLens](examples\u002Fmovielens)\n- [Generative adversarial networks](examples\u002Fgan)\n\n## API\n\nThis library follows the [PyTorch API](https:\u002F\u002Fpytorch.org\u002Fdocs\u002Fstable\u002Ftorch.html). There are a few changes to make it more Ruby-like:\n\n- Methods that perform in-place modifications end with `!` instead of `_` (`add!` instead of `add_`)\n- Methods that return booleans use `?` instead of `is_`  (`tensor?` instead of `is_tensor`)\n- Numo is used instead of NumPy (`x.numo` instead of `x.numpy()`)\n\nYou can follow PyTorch tutorials and convert the code to Ruby in many cases. Feel free to open an issue if you run into problems.\n\n## Overview\n\nSome examples below are from [Deep Learning with PyTorch: A 60 Minutes Blitz](https:\u002F\u002Fpytorch.org\u002Ftutorials\u002Fbeginner\u002Fdeep_learning_60min_blitz.html)\n\n### Tensors\n\nCreate a tensor from a Ruby array\n\n```ruby\nx = Torch.tensor([[1, 2, 3], [4, 5, 6]])\n```\n\nGet the shape of a tensor\n\n```ruby\nx.shape\n```\n\nThere are [many functions](#tensor-creation) to create tensors, like\n\n```ruby\na = Torch.rand(3)\nb = Torch.zeros(2, 3)\n```\n\nEach tensor has four properties\n\n- `dtype` - the data type - `:uint8`, `:int8`, `:int16`, `:int32`, `:int64`, `:float32`, `:float64`, or `:bool`\n- `layout` - `:strided` (dense) or `:sparse`\n- `device` - the compute device, like CPU or GPU\n- `requires_grad` - whether or not to record gradients\n\nYou can specify properties when creating a tensor\n\n```ruby\nTorch.rand(2, 3, dtype: :float64, layout: :strided, device: \"cpu\", requires_grad: true)\n```\n\n### Operations\n\nCreate a tensor\n\n```ruby\nx = Torch.tensor([10, 20, 30])\n```\n\nAdd\n\n```ruby\nx + 5 # tensor([15, 25, 35])\n```\n\nSubtract\n\n```ruby\nx - 5 # tensor([5, 15, 25])\n```\n\nMultiply\n\n```ruby\nx * 5 # tensor([50, 100, 150])\n```\n\nDivide\n\n```ruby\nx \u002F 5 # tensor([2, 4, 6])\n```\n\nGet the remainder\n\n```ruby\nx % 3 # tensor([1, 2, 0])\n```\n\nRaise to a power\n\n```ruby\nx**2 # tensor([100, 400, 900])\n```\n\nPerform operations with other tensors\n\n```ruby\ny = Torch.tensor([1, 2, 3])\nx + y # tensor([11, 22, 33])\n```\n\nPerform operations in-place\n\n```ruby\nx.add!(5)\nx # tensor([15, 25, 35])\n```\n\nYou can also specify an output tensor\n\n```ruby\nresult = Torch.empty(3)\nTorch.add(x, y, out: result)\nresult # tensor([15, 25, 35])\n```\n\n### Numo\n\nConvert a tensor to a Numo array\n\n```ruby\na = Torch.ones(5)\na.numo\n```\n\nConvert a Numo array to a tensor\n\n```ruby\nb = Numo::NArray.cast([1, 2, 3])\nTorch.from_numo(b)\n```\n\n### Autograd\n\nCreate a tensor with `requires_grad: true`\n\n```ruby\nx = Torch.ones(2, 2, requires_grad: true)\n```\n\nPerform operations\n\n```ruby\ny = x + 2\nz = y * y * 3\nout = z.mean\n```\n\nBackprop\n\n```ruby\nout.backward\n```\n\nGet gradients\n\n```ruby\nx.grad # tensor([[4.5, 4.5], [4.5, 4.5]])\n```\n\nStop autograd from tracking history\n\n```ruby\nx.requires_grad # true\n(x**2).requires_grad # true\n\nTorch.no_grad do\n  (x**2).requires_grad # false\nend\n```\n\n### Neural Networks\n\nDefine a neural network\n\n```ruby\nclass MyNet \u003C Torch::NN::Module\n  def initialize\n    super()\n    @conv1 = Torch::NN::Conv2d.new(1, 6, 3)\n    @conv2 = Torch::NN::Conv2d.new(6, 16, 3)\n    @fc1 = Torch::NN::Linear.new(16 * 6 * 6, 120)\n    @fc2 = Torch::NN::Linear.new(120, 84)\n    @fc3 = Torch::NN::Linear.new(84, 10)\n  end\n\n  def forward(x)\n    x = Torch::NN::F.max_pool2d(Torch::NN::F.relu(@conv1.call(x)), [2, 2])\n    x = Torch::NN::F.max_pool2d(Torch::NN::F.relu(@conv2.call(x)), 2)\n    x = Torch.flatten(x, 1)\n    x = Torch::NN::F.relu(@fc1.call(x))\n    x = Torch::NN::F.relu(@fc2.call(x))\n    @fc3.call(x)\n  end\nend\n```\n\nCreate an instance of it\n\n```ruby\nnet = MyNet.new\ninput = Torch.randn(1, 1, 32, 32)\nnet.call(input)\n```\n\nGet trainable parameters\n\n```ruby\nnet.parameters\n```\n\nZero the gradient buffers and backprop with random gradients\n\n```ruby\nnet.zero_grad\nout.backward(Torch.randn(1, 10))\n```\n\nDefine a loss function\n\n```ruby\noutput = net.call(input)\ntarget = Torch.randn(10)\ntarget = target.view(1, -1)\ncriterion = Torch::NN::MSELoss.new\nloss = criterion.call(output, target)\n```\n\nBackprop\n\n```ruby\nnet.zero_grad\np net.conv1.bias.grad\nloss.backward\np net.conv1.bias.grad\n```\n\nUpdate the weights\n\n```ruby\nlearning_rate = 0.01\nnet.parameters.each do |f|\n  f.data.sub!(f.grad.data * learning_rate)\nend\n```\n\nUse an optimizer\n\n```ruby\noptimizer = Torch::Optim::SGD.new(net.parameters, lr: 0.01)\noptimizer.zero_grad\noutput = net.call(input)\nloss = criterion.call(output, target)\nloss.backward\noptimizer.step\n```\n\n### Saving and Loading Models\n\nSave a model\n\n```ruby\nTorch.save(net.state_dict, \"net.pth\")\n```\n\nLoad a model\n\n```ruby\nnet = MyNet.new\nnet.load_state_dict(Torch.load(\"net.pth\"))\nnet.eval\n```\n\nWhen saving a model in Python to load in Ruby, convert parameters to tensors (due to outstanding bugs in LibTorch)\n\n```python\nstate_dict = {k: v.data if isinstance(v, torch.nn.Parameter) else v for k, v in state_dict.items()}\ntorch.save(state_dict, \"net.pth\")\n```\n\n### Tensor Creation\n\nHere’s a list of functions to create tensors (descriptions from the [C++ docs](https:\u002F\u002Fpytorch.org\u002Fcppdocs\u002Fnotes\u002Ftensor_creation.html)):\n\n- `arange` returns a tensor with a sequence of integers\n\n  ```ruby\n  Torch.arange(3) # tensor([0, 1, 2])\n  ```\n\n- `empty` returns a tensor with uninitialized values\n\n  ```ruby\n  Torch.empty(3) # tensor([7.0054e-45, 0.0000e+00, 0.0000e+00])\n  ```\n\n- `eye` returns an identity matrix\n\n  ```ruby\n  Torch.eye(2) # tensor([[1, 0], [0, 1]])\n  ```\n\n- `full` returns a tensor filled with a single value\n\n  ```ruby\n  Torch.full([3], 5) # tensor([5, 5, 5])\n  ```\n\n- `linspace` returns a tensor with values linearly spaced in some interval\n\n  ```ruby\n  Torch.linspace(0, 10, 5) # tensor([0, 5, 10])\n  ```\n\n- `logspace` returns a tensor with values logarithmically spaced in some interval\n\n  ```ruby\n  Torch.logspace(0, 10, 5) # tensor([1, 1e5, 1e10])\n  ```\n\n- `ones` returns a tensor filled with all ones\n\n  ```ruby\n  Torch.ones(3) # tensor([1, 1, 1])\n  ```\n\n- `rand` returns a tensor filled with values drawn from a uniform distribution on [0, 1)\n\n  ```ruby\n  Torch.rand(3) # tensor([0.5444, 0.8799, 0.5571])\n  ```\n\n- `randint` returns a tensor with integers randomly drawn from an interval\n\n  ```ruby\n  Torch.randint(1, 10, [3]) # tensor([7, 6, 4])\n  ```\n\n- `randn` returns a tensor filled with values drawn from a unit normal distribution\n\n  ```ruby\n  Torch.randn(3) # tensor([-0.7147,  0.6614,  1.1453])\n  ```\n\n- `randperm` returns a tensor filled with a random permutation of integers in some interval\n\n  ```ruby\n  Torch.randperm(3) # tensor([2, 0, 1])\n  ```\n\n- `zeros` returns a tensor filled with all zeros\n\n  ```ruby\n  Torch.zeros(3) # tensor([0, 0, 0])\n  ```\n\n## LibTorch Compatibility\n\nHere’s the list of compatible versions.\n\nTorch.rb | LibTorch\n--- | ---\n0.24.x | 2.11.x\n0.23.x | 2.10.x\n0.22.x | 2.9.x\n0.21.x | 2.8.x\n0.20.x | 2.7.x\n0.19.x | 2.6.x\n0.18.x | 2.5.x\n\n## Performance\n\nDeep learning is significantly faster on a GPU.\n\n### Linux\n\nWith Linux, install [CUDA](https:\u002F\u002Fdeveloper.nvidia.com\u002Fcuda-downloads) and [cuDNN](https:\u002F\u002Fdeveloper.nvidia.com\u002Fcudnn) and reinstall the gem.\n\nCheck if CUDA is available\n\n```ruby\nTorch::CUDA.available?\n```\n\nMove a neural network to a GPU\n\n```ruby\nnet.cuda\n```\n\nIf you don’t have a GPU that supports CUDA, we recommend using a cloud service. [Paperspace](https:\u002F\u002Fwww.paperspace.com\u002F) has a great free plan. We’ve put together a [Docker image](https:\u002F\u002Fgithub.com\u002Fankane\u002Fml-stack) to make it easy to get started. On Paperspace, create a notebook with a custom container. Under advanced options, set the container name to:\n\n```text\nankane\u002Fml-stack:torch-gpu\n```\n\nAnd leave the other fields in that section blank. Once the notebook is running, you can run the [MNIST example](https:\u002F\u002Fgithub.com\u002Fankane\u002Fml-stack\u002Fblob\u002Fmaster\u002Ftorch-gpu\u002FMNIST.ipynb).\n\n### Mac\n\nWith Apple silicon, check if Metal Performance Shaders (MPS) is available\n\n```ruby\nTorch::Backends::MPS.available?\n```\n\nMove a neural network to a GPU\n\n```ruby\ndevice = Torch.device(\"mps\")\nnet.to(device)\n```\n\n## History\n\nView the [changelog](https:\u002F\u002Fgithub.com\u002Fankane\u002Ftorch.rb\u002Fblob\u002Fmaster\u002FCHANGELOG.md)\n\n## Contributing\n\nEveryone is encouraged to help improve this project. Here are a few ways you can help:\n\n- [Report bugs](https:\u002F\u002Fgithub.com\u002Fankane\u002Ftorch.rb\u002Fissues)\n- Fix bugs and [submit pull requests](https:\u002F\u002Fgithub.com\u002Fankane\u002Ftorch.rb\u002Fpulls)\n- Write, clarify, or fix documentation\n- Suggest or add new features\n\nTo get started with development:\n\n```sh\ngit clone https:\u002F\u002Fgithub.com\u002Fankane\u002Ftorch.rb.git\ncd torch.rb\nbundle install\nbundle exec rake compile -- --with-torch-dir=\u002Fpath\u002Fto\u002Flibtorch\nbundle exec rake test\n```\n\nYou can use [this script](https:\u002F\u002Fgist.github.com\u002Fankane\u002F9b2b5fcbd66d6e4ccfeb9d73e529abe7) to test on GPUs with the AWS Deep Learning Base AMI (Ubuntu 18.04).\n\nHere are some good resources for contributors:\n\n- [PyTorch API](https:\u002F\u002Fpytorch.org\u002Fdocs\u002Fstable\u002Ftorch.html)\n- [PyTorch C++ API](https:\u002F\u002Fpytorch.org\u002Fcppdocs\u002F)\n- [Tensor Creation API](https:\u002F\u002Fpytorch.org\u002Fcppdocs\u002Fnotes\u002Ftensor_creation.html)\n- [Using the PyTorch C++ Frontend](https:\u002F\u002Fpytorch.org\u002Ftutorials\u002Fadvanced\u002Fcpp_frontend.html)\n","# Torch.rb\n\n:fire: 基于 [LibTorch](https:\u002F\u002Fpytorch.org) 的 Ruby 深度学习库\n\n你还可以查看：\n\n- [TorchVision](https:\u002F\u002Fgithub.com\u002Fankane\u002Ftorchvision-ruby) 用于计算机视觉任务\n- [TorchText](https:\u002F\u002Fgithub.com\u002Fankane\u002Ftorchtext-ruby) 用于文本和 NLP 任务\n- [TorchAudio](https:\u002F\u002Fgithub.com\u002Fankane\u002Ftorchaudio-ruby) 用于音频任务\n- [TorchCodec](https:\u002F\u002Fgithub.com\u002Fankane\u002Ftorchcodec-ruby) 用于音频和视频编码\n- [TorchRec](https:\u002F\u002Fgithub.com\u002Fankane\u002Ftorchrec-ruby) 用于推荐系统\n- [TorchData](https:\u002F\u002Fgithub.com\u002Fankane\u002Ftorchdata-ruby) 用于数据加载\n\n以及：\n\n- [Transformers](https:\u002F\u002Fgithub.com\u002Fankane\u002Ftransformers-ruby) 用于 Transformer 模型\n- [Safetensors](https:\u002F\u002Fgithub.com\u002Fankane\u002Fsafetensors-ruby) 用于存储张量\n\n[![构建状态](https:\u002F\u002Fgithub.com\u002Fankane\u002Ftorch.rb\u002Factions\u002Fworkflows\u002Fbuild.yml\u002Fbadge.svg)](https:\u002F\u002Fgithub.com\u002Fankane\u002Ftorch.rb\u002Factions)\n\n## 安装\n\n首先，[下载 LibTorch](https:\u002F\u002Fpytorch.org\u002Fget-started\u002Flocally\u002F)。对于 Mac arm64，请使用以下命令：\n\n```sh\ncurl -L https:\u002F\u002Fdownload.pytorch.org\u002Flibtorch\u002Fcpu\u002Flibtorch-macos-arm64-2.10.0.zip > libtorch.zip\nunzip -q libtorch.zip\n```\n\n对于 Linux x86-64，请使用与你的 CUDA 版本匹配的构建版本。对于其他平台，请从源代码编译 LibTorch。\n\n然后运行：\n\n```sh\nbundle config set build.torch-rb --with-torch-dir=\u002Fpath\u002Fto\u002Flibtorch\n```\n\n并在你的应用 Gemfile 中添加以下行：\n\n```ruby\ngem \"torch-rb\"\n```\n\n扩展编译可能需要 5–10 分钟。目前不支持 Windows。\n\n## 入门\n\n一个好的起点是 [用 Torch.rb 进行深度学习：60 分钟速成](tutorials\u002Fblitz\u002FREADME.md)。\n\n## 教程\n\n- [迁移学习](tutorials\u002Ftransfer_learning\u002FREADME.md)\n- [序列模型](tutorials\u002Fnlp\u002Fsequence_models.md)\n- [词嵌入](tutorials\u002Fnlp\u002Fword_embeddings.md)\n\n## 示例\n\n- [使用 MNIST 进行图像分类](examples\u002Fmnist)（[日文版](https:\u002F\u002Fqiita.com\u002Fkojix2\u002Fitems\u002Fc19c36dc1bf73ea93409)）\n- [使用 MovieLens 进行协同过滤](examples\u002Fmovielens)\n- [生成对抗网络](examples\u002Fgan)\n\n## API\n\n该库遵循 [PyTorch API](https:\u002F\u002Fpytorch.org\u002Fdocs\u002Fstable\u002Ftorch.html)。为了使其更符合 Ruby 风格，做了一些调整：\n\n- 执行原地修改的方法以 `!` 结尾，而不是 `_`（例如 `add!` 而不是 `add_`）\n- 返回布尔值的方法使用 `?` 而不是 `is_`（例如 `tensor?` 而不是 `is_tensor`）\n- 使用 Numo 替代 NumPy（例如 `x.numo` 而不是 `x.numpy()`）\n\n在许多情况下，你可以参考 PyTorch 教程并将代码转换为 Ruby。如果遇到问题，请随时提交 issue。\n\n## 概述\n\n以下示例摘自 [用 PyTorch 进行深度学习：60 分钟速成](https:\u002F\u002Fpytorch.org\u002Ftutorials\u002Fbeginner\u002Fdeep_learning_60min_blitz.html)。\n\n### 张量\n\n从 Ruby 数组创建张量\n\n```ruby\nx = Torch.tensor([[1, 2, 3], [4, 5, 6]])\n```\n\n获取张量的形状\n\n```ruby\nx.shape\n```\n\n还有 [许多函数](#tensor-creation) 可用于创建张量，例如：\n\n```ruby\na = Torch.rand(3)\nb = Torch.zeros(2, 3)\n```\n\n每个张量有四个属性：\n\n- `dtype` — 数据类型 — `:uint8`, `:int8`, `:int16`, `:int32`, `:int64`, `:float32`, `:float64`, 或 `:bool`\n- `layout` — `:strided`（密集）或 `:sparse`\n- `device` — 计算设备，如 CPU 或 GPU\n- `requires_grad` — 是否需要记录梯度\n\n你可以在创建张量时指定这些属性：\n\n```ruby\nTorch.rand(2, 3, dtype: :float64, layout: :strided, device: \"cpu\", requires_grad: true)\n```\n\n### 操作\n\n创建一个张量\n\n```ruby\nx = Torch.tensor([10, 20, 30])\n```\n\n加法\n\n```ruby\nx + 5 # tensor([15, 25, 35])\n```\n\n减法\n\n```ruby\nx - 5 # tensor([5, 15, 25])\n```\n\n乘法\n\n```ruby\nx * 5 # tensor([50, 100, 150])\n```\n\n除法\n\n```ruby\nx \u002F 5 # tensor([2, 4, 6])\n```\n\n取余数\n\n```ruby\nx % 3 # tensor([1, 2, 0])\n```\n\n求幂\n\n```ruby\nx**2 # tensor([100, 400, 900])\n```\n\n与其他张量进行操作\n\n```ruby\ny = Torch.tensor([1, 2, 3])\nx + y # tensor([11, 22, 33])\n```\n\n原地操作\n\n```ruby\nx.add!(5)\nx # tensor([15, 25, 35])\n```\n\n你也可以指定输出张量：\n\n```ruby\nresult = Torch.empty(3)\nTorch.add(x, y, out: result)\nresult # tensor([15, 25, 35])\n```\n\n### Numo\n\n将张量转换为 Numo 数组\n\n```ruby\na = Torch.ones(5)\na.numo\n```\n\n将 Numo 数组转换为张量\n\n```ruby\nb = Numo::NArray.cast([1, 2, 3])\nTorch.from_numo(b)\n```\n\n### 自动求导\n\n创建一个带有 `requires_grad: true` 的张量\n\n```ruby\nx = Torch.ones(2, 2, requires_grad: true)\n```\n\n执行操作\n\n```ruby\ny = x + 2\nz = y * y * 3\nout = z.mean\n```\n\n反向传播\n\n```ruby\nout.backward\n```\n\n获取梯度\n\n```ruby\nx.grad # tensor([[4.5, 4.5], [4.5, 4.5]])\n```\n\n停止自动求导跟踪历史\n\n```ruby\nx.requires_grad # true\n(x**2).requires_grad # true\n\nTorch.no_grad do\n  (x**2).requires_grad # false\nend\n```\n\n### 神经网络\n\n定义一个神经网络\n\n```ruby\nclass MyNet \u003C Torch::NN::Module\n  def initialize\n    super()\n    @conv1 = Torch::NN::Conv2d.new(1, 6, 3)\n    @conv2 = Torch::NN::Conv2d.new(6, 16, 3)\n    @fc1 = Torch::NN::Linear.new(16 * 6 * 6, 120)\n    @fc2 = Torch::NN::Linear.new(120, 84)\n    @fc3 = Torch::NN::Linear.new(84, 10)\n  end\n\n  def forward(x)\n    x = Torch::NN::F.max_pool2d(Torch::NN::F.relu(@conv1.call(x)), [2, 2])\n    x = Torch::NN::F.max_pool2d(Torch::NN::F.relu(@conv2.call(x)), 2)\n    x = Torch.flatten(x, 1)\n    x = Torch::NN::F.relu(@fc1.call(x))\n    x = Torch::NN::F.relu(@fc2.call(x))\n    @fc3.call(x)\n  end\nend\n```\n\n创建它的实例\n\n```ruby\nnet = MyNet.new\ninput = Torch.randn(1, 1, 32, 32)\nnet.call(input)\n```\n\n获取可训练参数\n\n```ruby\nnet.parameters\n```\n\n清零梯度缓冲区并用随机梯度反向传播\n\n```ruby\nnet.zero_grad\nout.backward(Torch.randn(1, 10))\n```\n\n定义损失函数\n\n```ruby\noutput = net.call(input)\ntarget = Torch.randn(10)\ntarget = target.view(1, -1)\ncriterion = Torch::NN::MSELoss.new\nloss = criterion.call(output, target)\n```\n\n反向传播\n\n```ruby\nnet.zero_grad\np net.conv1.bias.grad\nloss.backward\np net.conv1.bias.grad\n```\n\n更新权重\n\n```ruby\nlearning_rate = 0.01\nnet.parameters.each do |f|\n  f.data.sub!(f.grad.data * learning_rate)\nend\n```\n\n使用优化器\n\n```ruby\noptimizer = Torch::Optim::SGD.new(net.parameters, lr: 0.01)\noptimizer.zero_grad\noutput = net.call(input)\nloss = criterion.call(output, target)\nloss.backward\noptimizer.step\n```\n\n### 保存和加载模型\n\n保存模型\n\n```ruby\nTorch.save(net.state_dict, \"net.pth\")\n```\n\n加载模型\n\n```ruby\nnet = MyNet.new\nnet.load_state_dict(Torch.load(\"net.pth\"))\nnet.eval\n```\n\n当从 Python 保存模型以便在 Ruby 中加载时，由于 LibTorch 中存在未修复的 bug，需要将参数转换为张量：\n\n```python\nstate_dict = {k: v.data if isinstance(v, torch.nn.Parameter) else v for k, v in state_dict.items()}\ntorch.save(state_dict, \"net.pth\")\n```\n\n### 张量创建\n\n以下是用于创建张量的函数列表（描述来自 [C++ 文档](https:\u002F\u002Fpytorch.org\u002Fcppdocs\u002Fnotes\u002Ftensor_creation.html)）：\n\n- `arange` 返回一个包含整数序列的张量\n\n  ```ruby\n  Torch.arange(3) # tensor([0, 1, 2])\n  ```\n\n- `empty` 返回一个未初始化值的张量\n\n  ```ruby\n  Torch.empty(3) # tensor([7.0054e-45, 0.0000e+00, 0.0000e+00])\n  ```\n\n- `eye` 返回一个单位矩阵\n\n  ```ruby\n  Torch.eye(2) # tensor([[1, 0], [0, 1]])\n  ```\n\n- `full` 返回一个由单一值填充的张量\n\n  ```ruby\n  Torch.full([3], 5) # tensor([5, 5, 5])\n  ```\n\n- `linspace` 返回一个在某个区间内线性等距分布的张量\n\n  ```ruby\n  Torch.linspace(0, 10, 5) # tensor([0, 5, 10])\n  ```\n\n- `logspace` 返回一个在某个区间内对数等距分布的张量\n\n  ```ruby\n  Torch.logspace(0, 10, 5) # tensor([1, 1e5, 1e10])\n  ```\n\n- `ones` 返回一个全为 1 的张量\n\n  ```ruby\n  Torch.ones(3) # tensor([1, 1, 1])\n  ```\n\n- `rand` 返回一个由 [0, 1) 区间内的均匀分布随机数填充的张量\n\n  ```ruby\n  Torch.rand(3) # tensor([0.5444, 0.8799, 0.5571])\n  ```\n\n- `randint` 返回一个由指定区间内的随机整数组成的张量\n\n  ```ruby\n  Torch.randint(1, 10, [3]) # tensor([7, 6, 4])\n  ```\n\n- `randn` 返回一个由标准正态分布随机数填充的张量\n\n  ```ruby\n  Torch.randn(3) # tensor([-0.7147,  0.6614,  1.1453])\n  ```\n\n- `randperm` 返回一个由指定区间内整数的随机排列组成的张量\n\n  ```ruby\n  Torch.randperm(3) # tensor([2, 0, 1])\n  ```\n\n- `zeros` 返回一个全为 0 的张量\n\n  ```ruby\n  Torch.zeros(3) # tensor([0, 0, 0])\n  ```\n\n## LibTorch 兼容性\n\n以下是兼容版本列表。\n\nTorch.rb | LibTorch\n--- | ---\n0.24.x | 2.11.x\n0.23.x | 2.10.x\n0.22.x | 2.9.x\n0.21.x | 2.8.x\n0.20.x | 2.7.x\n0.19.x | 2.6.x\n0.18.x | 2.5.x\n\n## 性能\n\n深度学习在 GPU 上运行时速度显著更快。\n\n### Linux\n\n在 Linux 系统上，安装 [CUDA](https:\u002F\u002Fdeveloper.nvidia.com\u002Fcuda-downloads) 和 [cuDNN](https:\u002F\u002Fdeveloper.nvidia.com\u002Fcudnn)，然后重新安装 gem。\n\n检查 CUDA 是否可用：\n\n```ruby\nTorch::CUDA.available?\n```\n\n将神经网络移动到 GPU：\n\n```ruby\nnet.cuda\n```\n\n如果您没有支持 CUDA 的 GPU，建议使用云服务。[Paperspace](https:\u002F\u002Fwww.paperspace.com\u002F) 提供了一个非常好的免费方案。我们已经准备了一个 [Docker 镜像](https:\u002F\u002Fgithub.com\u002Fankane\u002Fml-stack)，方便您快速入门。在 Paperspace 上，创建一个自定义容器的笔记本。在高级选项中，将容器名称设置为：\n\n```text\nankane\u002Fml-stack:torch-gpu\n```\n\n并保持该部分的其他字段为空。笔记本启动后，您可以运行 [MNIST 示例](https:\u002F\u002Fgithub.com\u002Fankane\u002Fml-stack\u002Fblob\u002Fmaster\u002Ftorch-gpu\u002FMNIST.ipynb)。\n\n### Mac\n\n对于搭载 Apple 芯片的 Mac，检查 Metal Performance Shaders (MPS) 是否可用：\n\n```ruby\nTorch::Backends::MPS.available?\n```\n\n将神经网络移动到 GPU：\n\n```ruby\ndevice = Torch.device(\"mps\")\nnet.to(device)\n```\n\n## 历史\n\n查看 [变更日志](https:\u002F\u002Fgithub.com\u002Fankane\u002Ftorch.rb\u002Fblob\u002Fmaster\u002FCHANGELOG.md)\n\n## 贡献\n\n我们鼓励所有人帮助改进这个项目。以下是一些您可以参与的方式：\n\n- [报告问题](https:\u002F\u002Fgithub.com\u002Fankane\u002Ftorch.rb\u002Fissues)\n- 修复问题并 [提交拉取请求](https:\u002F\u002Fgithub.com\u002Fankane\u002Ftorch.rb\u002Fpulls)\n- 编写、澄清或修正文档\n- 提出或添加新功能\n\n要开始开发：\n\n```sh\ngit clone https:\u002F\u002Fgithub.com\u002Fankane\u002Ftorch.rb.git\ncd torch.rb\nbundle install\nbundle exec rake compile -- --with-torch-dir=\u002Fpath\u002Fto\u002Flibtorch\nbundle exec rake test\n```\n\n您可以使用 [此脚本](https:\u002F\u002Fgist.github.com\u002Fankane\u002F9b2b5fcbd66d6e4ccfeb9d73e529abe7) 在 AWS Deep Learning Base AMI（Ubuntu 18.04）上的 GPU 上进行测试。\n\n以下是一些对贡献者有帮助的资源：\n\n- [PyTorch API](https:\u002F\u002Fpytorch.org\u002Fdocs\u002Fstable\u002Ftorch.html)\n- [PyTorch C++ API](https:\u002F\u002Fpytorch.org\u002Fcppdocs\u002F)\n- [张量创建 API](https:\u002F\u002Fpytorch.org\u002Fcppdocs\u002Fnotes\u002Ftensor_creation.html)\n- [使用 PyTorch C++ 前端](https:\u002F\u002Fpytorch.org\u002Ftutorials\u002Fadvanced\u002Fcpp_frontend.html)","# Torch.rb 快速上手指南\n\nTorch.rb 是一个基于 LibTorch 的 Ruby 深度学习库，让 Ruby 开发者能够直接使用 PyTorch 的强大功能。\n\n## 环境准备\n\n### 系统要求\n- **操作系统**：Linux (x86-64) 或 macOS (arm64\u002Fx86_64)\n- **不支持**：Windows\n- **Ruby 版本**：需安装 Ruby 及 Bundler\n\n### 前置依赖\n在使用 gem 之前，必须先下载并配置 **LibTorch**。\n\n1. **macOS (Apple Silicon arm64)**\n   ```sh\n   curl -L https:\u002F\u002Fdownload.pytorch.org\u002Flibtorch\u002Fcpu\u002Flibtorch-macos-arm64-2.10.0.zip > libtorch.zip\n   unzip -q libtorch.zip\n   ```\n\n2. **Linux (x86-64)**\n   请访问 [PyTorch 官网](https:\u002F\u002Fpytorch.org\u002Fget-started\u002Flocally\u002F) 下载与你的 CUDA 版本匹配的 LibTorch 包。\n   *注：若无合适预编译包，需从源码构建 LibTorch。*\n\n3. **GPU 加速（可选）**\n   - **Linux**: 需安装 [CUDA](https:\u002F\u002Fdeveloper.nvidia.com\u002Fcuda-downloads) 和 [cuDNN](https:\u002F\u002Fdeveloper.nvidia.com\u002Fcudnn)。\n   - **macOS (Apple Silicon)**: 支持 MPS (Metal Performance Shaders) 后端。\n\n## 安装步骤\n\n1. **配置编译路径**\n   将 `\u002Fpath\u002Fto\u002Flibtorch` 替换为你实际解压 LibTorch 的目录路径：\n   ```sh\n   bundle config set build.torch-rb --with-torch-dir=\u002Fpath\u002Fto\u002Flibtorch\n   ```\n\n2. **添加依赖**\n   在项目的 `Gemfile` 中添加：\n   ```ruby\n   gem \"torch-rb\"\n   ```\n\n3. **安装 Gem**\n   运行以下命令进行安装（首次编译扩展可能需要 5-10 分钟）：\n   ```sh\n   bundle install\n   ```\n\n## 基本使用\n\nTorch.rb 的 API 设计高度遵循 PyTorch，但做了一些符合 Ruby 习惯的调整（如原地操作符以 `!` 结尾）。\n\n### 1. 创建张量 (Tensors)\n```ruby\nrequire 'torch'\n\n# 从 Ruby 数组创建张量\nx = Torch.tensor([[1, 2, 3], [4, 5, 6]])\n\n# 获取形状\nputs x.shape # => [2, 3]\n\n# 创建随机张量\na = Torch.rand(3)\nb = Torch.zeros(2, 3)\n```\n\n### 2. 基本运算\n```ruby\nx = Torch.tensor([10, 20, 30])\n\n# 加减乘除\nputs x + 5       # tensor([15, 25, 35])\nputs x * 5       # tensor([50, 100, 150])\n\n# 原地操作 (注意末尾的 !)\nx.add!(5)\nputs x           # tensor([15, 25, 35])\n\n# 与其他张量运算\ny = Torch.tensor([1, 2, 3])\nputs x + y       # tensor([16, 27, 38])\n```\n\n### 3. 自动求导 (Autograd)\n```ruby\n# 创建需要梯度的张量\nx = Torch.ones(2, 2, requires_grad: true)\n\n# 构建计算图\ny = x + 2\nz = y * y * 3\nout = z.mean\n\n# 反向传播\nout.backward\n\n# 获取梯度\nputs x.grad \n# => tensor([[4.5, 4.5], [4.5, 4.5]])\n```\n\n### 4. 定义神经网络\n```ruby\nclass MyNet \u003C Torch::NN::Module\n  def initialize\n    super()\n    @fc1 = Torch::NN::Linear.new(10, 5)\n    @fc2 = Torch::NN::Linear.new(5, 2)\n  end\n\n  def forward(x)\n    x = Torch::NN::F.relu(@fc1.call(x))\n    @fc2.call(x)\n  end\nend\n\n# 实例化并使用\nnet = MyNet.new\ninput = Torch.randn(1, 10)\noutput = net.call(input)\n\n# 获取参数\nparams = net.parameters\n```\n\n### 5. 训练循环示例\n```ruby\ncriterion = Torch::NN::MSELoss.new\noptimizer = Torch::Optim::SGD.new(net.parameters, lr: 0.01)\n\n# 模拟一次迭代\noptimizer.zero_grad\noutput = net.call(input)\ntarget = Torch.randn(1, 2)\nloss = criterion.call(output, target)\nloss.backward\noptimizer.step\n```\n\n### 6. GPU 加速\n```ruby\n# Linux (CUDA)\nif Torch::CUDA.available?\n  net.cuda\nend\n\n# macOS (MPS)\nif Torch::Backends::MPS.available?\n  device = Torch.device(\"mps\")\n  net.to(device)\nend\n```","一家专注于电商推荐的初创团队，希望在其现有的 Ruby on Rails 后端系统中直接集成深度学习模型，以实时预测用户可能喜欢的商品。\n\n### 没有 torch.rb 时\n- **架构割裂严重**：数据科学家需用 Python 训练模型，而业务逻辑在 Ruby 中，导致必须搭建额外的 Python 微服务或通过复杂的 API 进行通信，增加了系统维护成本。\n- **开发效率低下**：工程师需要在两种语言间反复切换上下文，调试时需同时监控 Ruby 日志和 Python 进程，排查问题耗时费力。\n- **部署复杂度高**：生产环境需同时维护 Ruby 和 Python 两套运行时依赖，容器镜像体积庞大，且容易因版本冲突导致服务不稳定。\n- **实时性受限**：跨语言调用带来的网络延迟和序列化开销，使得毫秒级的实时推荐响应难以保证。\n\n### 使用 torch.rb 后\n- **原生无缝集成**：直接在 Ruby 代码中调用 LibTorch 引擎，无需外部服务，利用 `Torch.tensor` 即可在 Rails 控制器中完成张量运算与模型推理。\n- **统一技术栈**：团队成员只需专注 Ruby 生态，利用熟悉的语法（如 `add!` 代替 `add_`）编写深度学习逻辑，大幅降低学习曲线和沟通成本。\n- **轻量化部署**：移除了 Python 运行时依赖，显著减小了 Docker 镜像体积，简化了 CI\u002FCD 流程，提升了服务器资源利用率。\n- **极致性能体验**：消除了跨语言调用的网络开销，模型推理直接在应用进程内执行，轻松满足高并发下的低延迟推荐需求。\n\ntorch.rb 打破了语言壁垒，让 Ruby 开发者能像编写普通业务代码一样高效构建和部署高性能深度学习应用。","https:\u002F\u002Foss.gittoolsai.com\u002Fimages\u002Fankane_torch.rb_988ba605.png","ankane","Andrew Kane","https:\u002F\u002Foss.gittoolsai.com\u002Favatars\u002Fankane_502ffadf.jpg",null,"San Francisco, CA","andrew@ankane.org","https:\u002F\u002Fankane.org","https:\u002F\u002Fgithub.com\u002Fankane",[84,88],{"name":85,"color":86,"percentage":87},"Ruby","#701516",78.9,{"name":89,"color":90,"percentage":91},"C++","#f34b7d",21.1,828,37,"2026-04-02T00:37:15","NOASSERTION",4,"Linux, macOS","非必需。Linux 需安装匹配的 CUDA 和 cuDNN 以启用 GPU；macOS (Apple Silicon) 支持 MPS 后端。未指定具体显存大小或最低显卡型号。","未说明",{"notes":101,"python":102,"dependencies":103},"不支持 Windows。需手动下载 LibTorch 并配置编译路径。编译扩展可能需要 5-10 分钟。若要在 Linux 上使用 GPU，需根据 CUDA 版本下载对应的 LibTorch 构建版；若无兼容 GPU，建议使用云服务。","不需要 (基于 Ruby)",[104,85,105],"LibTorch (版本需与 torch.rb 严格匹配，如 0.24.x 对应 2.11.x)","Numo::NArray",[13],"2026-03-27T02:49:30.150509","2026-04-06T08:17:44.435082",[110,115,120,125,130,134],{"id":111,"question_zh":112,"answer_zh":113,"source_url":114},15305,"在 macOS 上安装 gem 时遇到 clang 错误：'unsupported option -fopenmp'，如何解决？","这通常是因为 Ruby 安装环境与系统编译器不兼容导致的。解决方案是重新安装一个干净的 Ruby 版本。例如使用 RVM：\n1. 运行 `rvm install 2.6.9`（或先移除旧版本 `rvm remove 2.6.6` 再重新安装）。\n2. 确保 libtorch 版本与 gem 版本兼容。如果仍在使用 libtorch 1.9.0，请安装对应的 gem 版本：`gem install torch-rb -v 0.8.3`。\n3. 验证编译器版本：`ruby -e 'puts RbConfig::CONFIG[\"CC_VERSION_MESSAGE\"]'`，确认使用的是正确的 Apple clang 版本。","https:\u002F\u002Fgithub.com\u002Fankane\u002Ftorch.rb\u002Fissues\u002F26",{"id":116,"question_zh":117,"answer_zh":118,"source_url":119},15306,"在 macOS 上加载 torch 时出现段错误（SEGV），如何修复？","段错误通常是由于 gem 链接了 macOS 系统的 libc++，而 Ruby 是通过 Homebrew 编译并链接了 Homebrew 的 libc++ 造成的冲突。解决方法有两种：\n\n方法一（推荐）：卸载通过 Homebrew 安装的 LLVM。\n```bash\nbrew uninstall llvm --ignore-dependencies\n```\n然后重新安装 Ruby 并启用共享库：\n```bash\nruby-install ruby 4.0.1 -- --enable-shared\n```\n最后清理并重新编译项目：\n```bash\nrm -rfv vendor\u002Fbundle\nbundle install\nbundle exec rake clean compile -- --with-torch-dir=~\u002Fsrc\u002Flibtorch\n```\n\n方法二（手动指定链接标志）：如果不卸载 LLVM，可以在编译时显式指定 LLVM 的路径和链接标志：\n```bash\nLLVM_PREFIX=\"$(brew --prefix llvm)\"\nLDFLAGS=\"-stdlib=libc++ -Wl,-rpath,${LLVM_PREFIX}\u002Flib\u002Fc++ -Wl,-rpath,${LLVM_PREFIX}\u002Flib\u002Funwind ${LLVM_PREFIX}\u002Flib\u002Fc++\u002Flibc++.1.dylib ${LLVM_PREFIX}\u002Flib\u002Fc++\u002Flibc++abi.1.dylib ${LLVM_PREFIX}\u002Flib\u002Funwind\u002Flibunwind.1.dylib\"\n```\n然后使用以下命令安装或配置：\n```bash\n# 使用 Bundler\nbundle config set --local build.torch-rb \"--with-torch-dir=$HOME\u002Fsrc\u002Flibtorch --with-ldflags=$LDFLAGS\"\nbundle install\n\n# 或直接使用 gem install\ngem install torch-rb -- \"--with-torch-dir=$HOME\u002Fsrc\u002Flibtorch --with-ldflags=$LDFLAGS\"\n```","https:\u002F\u002Fgithub.com\u002Fankane\u002Ftorch.rb\u002Fissues\u002F75",{"id":121,"question_zh":122,"answer_zh":123,"source_url":124},15307,"编译时报错 'Incompatible LibTorch version'（LibTorch 版本不兼容）怎么办？","该错误表明当前安装的 LibTorch 版本与 torch.rb 要求的版本不一致。对于 Linux 上使用 Homebrew 的用户，现在的 torch.rb 已经自动检查 `\u002Fhome\u002Flinuxbrew\u002F.linuxbrew` 路径，因此通常不需要额外配置环境变量即可自动找到正确的库。如果遇到此问题，请确保已通过 Homebrew 正确安装了 libtorch，并且没有手动设置冲突的环境变量。","https:\u002F\u002Fgithub.com\u002Fankane\u002Ftorch.rb\u002Fissues\u002F34",{"id":126,"question_zh":127,"answer_zh":128,"source_url":129},15308,"如何在多 GPU 环境或分布式设置中测试 torch.rb？","目前官方尚未完全实现分布式处理功能，但社区用户正在积极探讨。如果您拥有多 GPU 机器（如 4x, 6x, 14x GPU 构建），可以协助测试分布式数据并行实现（如 NCCL, GLOO, MPI）。您可以从使用库开始，在实际使用中发现问题并提交贡献。维护者表示尚未在分布式处理方面开展工作，欢迎社区成员一起探索和实施相关功能。","https:\u002F\u002Fgithub.com\u002Fankane\u002Ftorch.rb\u002Fissues\u002F1",{"id":131,"question_zh":132,"answer_zh":133,"source_url":129},15309,"为什么比较运算符（如 ==, >, \u003C）返回的结果在 Ruby 中表现奇怪？","这是设计决定。在 Python 中，张量比较返回一个张量，但在 Ruby 中，如果 `Torch.tensor(0) == 1` 返回一个张量对象，Ruby 会将其视为真值（truthy），这会导致逻辑错误且无法重写真值判断行为。因此，torch.rb 决定不支持直接返回张量的比较运算符，以避免这种语义混淆。",{"id":135,"question_zh":136,"answer_zh":137,"source_url":129},15310,"新手如何开始为 torch.rb 项目做贡献？","即使没有深厚的专业知识，新手也可以通过以下方式参与：\n1. 查看项目规划（Plan）中的待办事项列表，寻找标记为简单任务的项目入手。\n2. 开始实际使用这个库，在使用过程中遇到问题或发现改进点时提交 Issue 或 PR。\n3. 如果有特定硬件资源（如多 GPU 机器），可以协助进行特定环境的测试。\n维护者鼓励用户边用边学，通过解决实际问题来深入理解复杂概念。",[]]