{"id":16272005,"url":"https://github.com/logcreative/custom-tensor-op","last_synced_at":"2025-07-24T21:35:18.419Z","repository":{"id":168638047,"uuid":"427913073","full_name":"LogCreative/custom-tensor-op","owner":"LogCreative","description":null,"archived":false,"fork":false,"pushed_at":"2022-01-23T02:19:04.000Z","size":4520,"stargazers_count":2,"open_issues_count":0,"forks_count":0,"subscribers_count":1,"default_branch":"main","last_synced_at":"2025-04-08T15:50:13.726Z","etag":null,"topics":[],"latest_commit_sha":null,"homepage":"","language":"Python","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"mit","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/LogCreative.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":"LICENSE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null}},"created_at":"2021-11-14T11:44:44.000Z","updated_at":"2022-04-19T07:31:10.000Z","dependencies_parsed_at":null,"dependency_job_id":"b761956c-ce5e-423e-998f-e150475658e6","html_url":"https://github.com/LogCreative/custom-tensor-op","commit_stats":null,"previous_names":["logcreative/custom-tensor-op"],"tags_count":0,"template":false,"template_full_name":null,"purl":"pkg:github/LogCreative/custom-tensor-op","repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/LogCreative%2Fcustom-tensor-op","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/LogCreative%2Fcustom-tensor-op/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/LogCreative%2Fcustom-tensor-op/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/LogCreative%2Fcustom-tensor-op/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/LogCreative","download_url":"https://codeload.github.com/LogCreative/custom-tensor-op/tar.gz/refs/heads/main","sbom_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/LogCreative%2Fcustom-tensor-op/sbom","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":266905598,"owners_count":24004148,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","status":"online","status_checked_at":"2025-07-24T02:00:09.469Z","response_time":99,"last_error":null,"robots_txt_status":"success","robots_txt_updated_at":"2025-07-24T06:49:26.215Z","robots_txt_url":"https://github.com/robots.txt","online":true,"can_crawl_api":true,"host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":[],"created_at":"2024-10-10T18:15:44.951Z","updated_at":"2025-07-24T21:35:18.394Z","avatar_url":"https://github.com/LogCreative.png","language":"Python","funding_links":[],"categories":[],"sub_categories":[],"readme":"# custom-tensor-op\r\n\r\n\r\n## 运行情况\r\n\r\n### Linear 层\r\n\r\nLinear 层已经被实现，所以在此仅给出运行情况：\r\n\r\n||||\r\n|--------|--------------|--------------------------|\r\n|硬件环境|CPU（vCPU数目）|4(8)|\r\n||GPU(型号，数目)| GTX 1050 Ti x1|\r\n|软件环境|OS版本|Windows 11|\r\n||深度学习框架\u003cbr\u003epython包名称及版本|torch==1.10.0|\r\n||CUDA版本|11.5|\r\n||||\r\n\r\n||||\r\n|---------------|---------------------------|-----|\r\n| 实现方式（Linear层）| 性能评测 | 单次时间 |\r\n|\u003cbr/\u003e \u003cbr/\u003ePyTorch原有张量运算\u003cbr/\u003e \u003cbr/\u003e\u0026nbsp;| 9905/10000 221s | 34.5s |\r\n|\u003cbr/\u003e \u003cbr/\u003e基于Python API的定制化张量运算\u003cbr/\u003e \u003cbr/\u003e\u0026nbsp;|9914/10000  218s| 33.2s |\r\n|\u003cbr/\u003e \u003cbr/\u003e基于C++的定制化张量运算\u003cbr/\u003e \u003cbr/\u003e\u0026nbsp;|9909/10000 221s| 32.6s |\r\n||||\r\n\r\n线性层的自定义可以在一定程度上加快速度。\r\n\r\n### Conv2d 层\r\n\r\nConv2d 的运行情况\r\n\r\n||||\r\n|---------------|---------------------------|---|\r\n| 实现方式（Conv2d层）| 性能评测 | 单次时间* |\r\n|\u003cbr/\u003e \u003cbr/\u003ePyTorch原有张量运算\u003cbr/\u003e \u003cbr/\u003e\u0026nbsp;|9905/10000 221s| 35.3s |\r\n|\u003cbr/\u003e \u003cbr/\u003e基于Python API的定制化张量运算\u003cbr/\u003e \u003cbr/\u003e\u0026nbsp;|9907/10000  235s| 39.1s |\r\n|\u003cbr/\u003e \u003cbr/\u003e基于C++的定制化张量运算\u003cbr/\u003e \u003cbr/\u003e\u0026nbsp;|9907/10000 234s| 39.1s |\r\n|||||\r\n\r\n\u003cdiv style=\"font-size: small\"\u003e*单次时间没有取平均，更加细致的时间分析将会采用下面的方法。\u003c/div\u003e\r\n\r\n使用 [convperf](task/convperf.py) 对卷积层的测试结果如下（5000次取平均）：\r\n\r\n|CPU 测试结果 |              Forward     |    Forward+Backward|\r\n|---|---|---|\r\n|native  | 0.006395 |    0.014766 |\r\n|pyver   | 0.006491 |    0.019503 |\r\n|cppver  | 0.006585 |    0.019705 |\r\n\r\n\r\n|CUDA 测试结果 |               Forward   |      Forward+Backward|\r\n|---|---|---|\r\n|native |  0.001082  | 0.001365 |\r\n|pyver  |  0.001043  | 0.003303 |\r\n|cppver |  0.001108  | 0.003151 |\r\n\r\n不论是实际地在 MNIST 环境中训练得到的结果，还是纯净测试得到的结果，都可以看到自定义实现的 Python 版本和 C++ 版本在含反向传播上差别不大（最终结果），比原生的版本都慢一些。\r\n\r\n[Profiler](task/mnist_conv_benchmark.py) 的分析（CUDA）显示是卷积调用次数过多导致，自定义实现的函数仍有可优化空间。在上表的结果可以发现，Forward层面基本没有区别（毕竟都只是调用 F.conv），但是 Forward+Backward 在 CPU 上慢了 33%，在 CUDA 上慢了 141%。这也就意味着自动图运算生成的反向传播算法可以减少卷积顶层调用的次数，类似于编译优化，虽然手动编写反向传播是可行的，但是对于专用运算器使用专用的方法进行优化会更好，下表 Profiler 的结果显示在 Backward 上并没有使用 Conv2d。\r\n\r\n||# of Calls (aten::conv2d)|\r\n|--|--|\r\n|native|1896|\r\n|pyver|5648|\r\n\r\n|Native Run over CUDA| # of Calls |\r\n|--|--|\r\n| aten::cudnn_convolution_backward | 1876 |\r\n\r\n而是使用了内置的 cudnn_convolution_backward 实现，调用一次即可得到结果，猜测在数据并行性上有了较好的优化，直接输入一次数据，就执行两次等价时间的卷积运算，更好地提高硬件利用率。\r\n\r\n对于 CPU 优化而言，可以使用 TVM 对循环结构进行调整，减少数据依赖性，提高硬件利用率，提高 60% 左右的效率。细节详见 [LogCreative/CompilerPrinciple](https://github.com/LogCreative/CompilerPrinciple) 。\r\n\r\n## 卷积层原理\r\n\r\n[Pytorch的API](https://pytorch.org/docs/master/generated/torch.nn.Conv2d.html#torch.nn.Conv2d) 告诉我们\r\n```python\r\ntorch.nn.Conv2d(in_channels, out_channels, kernel_size, \r\nstride=1, padding=0, dilation=1, groups=1, \r\nbias=True, padding_mode='zeros', \r\ndevice=None, dtype=None)\r\n```\r\n检视 MNIST 代码后发现我们可以直接使用后面所有的默认值，不需要实现全部的参数。所以本项目的函数原型为\r\n```python\r\nmyConv2d(in_channels, out_channels, kernel_size)\r\n```\r\n\r\n然后仿照线性层，实现`myConv2dFunction`调用函数的`forward`和`backward`函数。\r\n\r\n见[卷积推导](https://logcreative.github.io/custom-tensor-op/img/conv.pdf)（PDF）。对应的细节的下标实现见 [CPU 版本](task/custom_conv2d_cpu.py)，但请注意该模块不能在 GPU 版本中运行成功，有数据传输问题，为避免此将直接通过下一节的 Pytorch API 实现。该代码仅供展示原理，并且在 Python 层直接运算矩阵会有精度问题。代码一定程度参考[配套代码](https://github.com/microsoft/ai-edu/blob/master/%E5%9F%BA%E7%A1%80%E6%95%99%E7%A8%8B/A2-%E7%A5%9E%E7%BB%8F%E7%BD%91%E7%BB%9C%E5%9F%BA%E6%9C%AC%E5%8E%9F%E7%90%86/%E7%AC%AC8%E6%AD%A5%20-%20%E5%8D%B7%E7%A7%AF%E7%A5%9E%E7%BB%8F%E7%BD%91%E7%BB%9C/src/ch17-CNNBasic/MiniFramework/ConvLayer.py)。\r\n\r\n## Python 版本实现\r\n\r\n运行方法\r\n\r\n```cmd\r\ncd task\r\npython mnist_custom_conv2d.py\r\n```\r\n\r\n为了转换为 GPU 可以处理的[代码](task/custom_conv2d.py)，需要统一下标的处理方式，以直接使用 `F.conv2d` 函数，会使用 `transpose` 进行处理。\r\n\r\n## C++ 版本实现\r\n\r\n运行方法\r\n\r\n```cmd\r\ncd task/myconv2d_cpp\r\npython setup.py install --user\r\ncd ..\r\npython mnist_custom_conv2d_cpp.py\r\n```\r\n\r\n[代码](task/myconv2d_cpp/myconv2d.cpp)结构与 Python 版本类似，但是需要注意`conv2d`在c++中的调用方式可选参数需要使用`Conv2dFuncOptions`包裹。\r\n\r\n本项目含有[单元测试](task/convtest.py)。","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Flogcreative%2Fcustom-tensor-op","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Flogcreative%2Fcustom-tensor-op","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Flogcreative%2Fcustom-tensor-op/lists"}