torch-friends 1.0.0__tar.gz
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- torch_friends-1.0.0/CMakeLists.txt +89 -0
- torch_friends-1.0.0/MANIFEST.in +6 -0
- torch_friends-1.0.0/PKG-INFO +246 -0
- torch_friends-1.0.0/README.md +223 -0
- torch_friends-1.0.0/binding/bind.cpp +75 -0
- torch_friends-1.0.0/include/torch_tools/rope.hpp +286 -0
- torch_friends-1.0.0/pyproject.toml +3 -0
- torch_friends-1.0.0/setup.cfg +4 -0
- torch_friends-1.0.0/setup.py +78 -0
- torch_friends-1.0.0/src/rope.cpp +339 -0
- torch_friends-1.0.0/src/rope_cuda.cu +214 -0
- torch_friends-1.0.0/torch_friends.egg-info/PKG-INFO +246 -0
- torch_friends-1.0.0/torch_friends.egg-info/SOURCES.txt +19 -0
- torch_friends-1.0.0/torch_friends.egg-info/dependency_links.txt +1 -0
- torch_friends-1.0.0/torch_friends.egg-info/not-zip-safe +1 -0
- torch_friends-1.0.0/torch_friends.egg-info/requires.txt +1 -0
- torch_friends-1.0.0/torch_friends.egg-info/top_level.txt +1 -0
- torch_friends-1.0.0/torch_tools/__init__.py +7 -0
- torch_friends-1.0.0/torch_tools/rope.py +49 -0
- torch_friends-1.0.0/torch_tools/torch_tools_cpp.cpython-312-x86_64-linux-gnu.so +0 -0
- torch_friends-1.0.0/torch_tools/torch_tools_cpp.pyi +0 -0
|
@@ -0,0 +1,89 @@
|
|
|
1
|
+
cmake_minimum_required(VERSION 3.18 FATAL_ERROR)
|
|
2
|
+
project(torch_friend VERSION 1.0.0 LANGUAGES CXX)
|
|
3
|
+
|
|
4
|
+
set(CMAKE_CXX_STANDARD 20)
|
|
5
|
+
set(CMAKE_CXX_STANDARD_REQUIRED ON)
|
|
6
|
+
set(CMAKE_CXX_EXTENSIONS OFF)
|
|
7
|
+
|
|
8
|
+
if(MSVC)
|
|
9
|
+
add_compile_options(/O2 /fp:fast /arch:AVX2)
|
|
10
|
+
else()
|
|
11
|
+
add_compile_options(-O3 -march=native -ffast-math -Wall -Wextra -Wno-stringop-overflow -Wno-array-bounds)
|
|
12
|
+
endif()
|
|
13
|
+
|
|
14
|
+
option(USE_CUDA "Enable CUDA acceleration for NVIDIA GPUs" OFF)
|
|
15
|
+
option(BUILD_EXAMPLES "Build standalone C++ examples" OFF)
|
|
16
|
+
|
|
17
|
+
# 1. Find Torch, Python3, and OpenMP
|
|
18
|
+
find_package(Torch REQUIRED)
|
|
19
|
+
find_package(Python3 REQUIRED COMPONENTS Interpreter Development)
|
|
20
|
+
find_package(OpenMP REQUIRED)
|
|
21
|
+
|
|
22
|
+
# 2. Locate libtorch_python.so
|
|
23
|
+
find_library(TORCH_PYTHON_LIBRARY torch_python PATHS "${TORCH_INSTALL_PREFIX}/lib" NO_DEFAULT_PATH)
|
|
24
|
+
if(NOT TORCH_PYTHON_LIBRARY)
|
|
25
|
+
message(FATAL_ERROR "Could not find libtorch_python.so in ${TORCH_INSTALL_PREFIX}/lib")
|
|
26
|
+
endif()
|
|
27
|
+
|
|
28
|
+
include_directories(${CMAKE_CURRENT_SOURCE_DIR}/include)
|
|
29
|
+
include_directories(${TORCH_INCLUDE_DIRS})
|
|
30
|
+
include_directories(${Python3_INCLUDE_DIRS})
|
|
31
|
+
|
|
32
|
+
set(TORCH_TOOLS_SOURCES src/rope.cpp)
|
|
33
|
+
|
|
34
|
+
if(USE_CUDA)
|
|
35
|
+
include(CheckLanguage)
|
|
36
|
+
check_language(CUDA)
|
|
37
|
+
if(CMAKE_CUDA_COMPILER)
|
|
38
|
+
enable_language(CUDA)
|
|
39
|
+
set(CMAKE_CUDA_STANDARD 17)
|
|
40
|
+
set(CMAKE_CUDA_FLAGS "${CMAKE_CUDA_FLAGS} -O3 --use_fast_math")
|
|
41
|
+
list(APPEND TORCH_TOOLS_SOURCES src/rope_cuda.cu)
|
|
42
|
+
add_definitions(-DUSE_CUDA)
|
|
43
|
+
else()
|
|
44
|
+
message(WARNING "CUDA compiler not found. Falling back to CPU.")
|
|
45
|
+
set(USE_CUDA OFF)
|
|
46
|
+
endif()
|
|
47
|
+
endif()
|
|
48
|
+
|
|
49
|
+
# 3. Core Static Library
|
|
50
|
+
add_library(torch_tools STATIC ${TORCH_TOOLS_SOURCES})
|
|
51
|
+
set_target_properties(torch_tools PROPERTIES POSITION_INDEPENDENT_CODE ON)
|
|
52
|
+
target_link_libraries(torch_tools PRIVATE ${TORCH_LIBRARIES})
|
|
53
|
+
if(OpenMP_CXX_FOUND)
|
|
54
|
+
target_link_libraries(torch_tools PRIVATE OpenMP::OpenMP_CXX)
|
|
55
|
+
endif()
|
|
56
|
+
|
|
57
|
+
# 4. Python Shared Extension Module
|
|
58
|
+
add_library(torch_tools_cpp MODULE binding/bind.cpp)
|
|
59
|
+
target_compile_definitions(torch_tools_cpp PRIVATE TORCH_EXTENSION_NAME=torch_tools_cpp)
|
|
60
|
+
|
|
61
|
+
target_link_libraries(torch_tools_cpp PRIVATE
|
|
62
|
+
torch_tools
|
|
63
|
+
${TORCH_LIBRARIES}
|
|
64
|
+
${TORCH_PYTHON_LIBRARY}
|
|
65
|
+
)
|
|
66
|
+
if(OpenMP_CXX_FOUND)
|
|
67
|
+
target_link_libraries(torch_tools_cpp PRIVATE OpenMP::OpenMP_CXX)
|
|
68
|
+
endif()
|
|
69
|
+
|
|
70
|
+
# Default to .so for manual CMake builds, or use Python's PEP 3149 suffix when called from setup.py
|
|
71
|
+
if(NOT DEFINED PYTHON_EXT_SUFFIX)
|
|
72
|
+
set(PYTHON_EXT_SUFFIX ".so")
|
|
73
|
+
endif()
|
|
74
|
+
|
|
75
|
+
set_target_properties(torch_tools_cpp PROPERTIES
|
|
76
|
+
PREFIX ""
|
|
77
|
+
SUFFIX "${PYTHON_EXT_SUFFIX}"
|
|
78
|
+
BUILD_WITH_INSTALL_RPATH TRUE
|
|
79
|
+
INSTALL_RPATH "$ORIGIN/../torch/lib;${TORCH_INSTALL_PREFIX}/lib"
|
|
80
|
+
)
|
|
81
|
+
|
|
82
|
+
# 5. Optional C++ Example
|
|
83
|
+
if(BUILD_EXAMPLES AND EXISTS "${CMAKE_CURRENT_SOURCE_DIR}/examples/main.cpp")
|
|
84
|
+
add_executable(run_rope examples/main.cpp)
|
|
85
|
+
target_link_libraries(run_rope PRIVATE torch_tools ${TORCH_LIBRARIES})
|
|
86
|
+
if(OpenMP_CXX_FOUND)
|
|
87
|
+
target_link_libraries(run_rope PRIVATE OpenMP::OpenMP_CXX)
|
|
88
|
+
endif()
|
|
89
|
+
endif()
|
|
@@ -0,0 +1,246 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: torch-friends
|
|
3
|
+
Version: 1.0.0
|
|
4
|
+
Summary: Ultra-optimized C++/LibTorch Rotary Position Embedding (RoPE) for CPU and CUDA
|
|
5
|
+
Home-page: https://github.com/ANSH-ind
|
|
6
|
+
Author: Ansh Raj
|
|
7
|
+
Author-email: anshraj0000000001@gmail.com
|
|
8
|
+
Classifier: Programming Language :: Python :: 3
|
|
9
|
+
Classifier: Programming Language :: C++
|
|
10
|
+
Classifier: Topic :: Scientific/Engineering :: Artificial Intelligence
|
|
11
|
+
Requires-Python: >=3.9
|
|
12
|
+
Description-Content-Type: text/markdown
|
|
13
|
+
Requires-Dist: torch>=2.0
|
|
14
|
+
Dynamic: author
|
|
15
|
+
Dynamic: author-email
|
|
16
|
+
Dynamic: classifier
|
|
17
|
+
Dynamic: description
|
|
18
|
+
Dynamic: description-content-type
|
|
19
|
+
Dynamic: home-page
|
|
20
|
+
Dynamic: requires-dist
|
|
21
|
+
Dynamic: requires-python
|
|
22
|
+
Dynamic: summary
|
|
23
|
+
|
|
24
|
+
# ⚡ torch-tools
|
|
25
|
+
|
|
26
|
+
**High-Performance C++20, OpenMP, and CUDA Extensions for PyTorch**
|
|
27
|
+
|
|
28
|
+
[](https://pypi.org/project/torch-tools/)
|
|
29
|
+
[](https://en.cppreference.com/w/cpp/20)
|
|
30
|
+
[](https://pytorch.org/)
|
|
31
|
+
[](https://opensource.org/licenses/MIT)
|
|
32
|
+
|
|
33
|
+
`torch-tools` is a native C++/LibTorch operator library built to accelerate modern Deep Learning and Transformer workloads in PyTorch. Instead of relying on memory-bound Python operations, `torch-tools` executes fused kernels directly in C++20 (using OpenMP multithreading and SIMD vectorization on CPU) and custom CUDA kernels on NVIDIA GPUs.
|
|
34
|
+
|
|
35
|
+
> **📢 Project Status:** **Rotary Position Embedding (RoPE)** is 100% complete, tested, and production-ready! `torch-tools` is an actively growing ecosystem—many more custom C++/CUDA neural network primitives, fused normalization layers, and PyTorch utilities are on the way.
|
|
36
|
+
|
|
37
|
+
---
|
|
38
|
+
|
|
39
|
+
## ✨ Key Highlights
|
|
40
|
+
|
|
41
|
+
- **Zero-Overhead C++20 & LibTorch Backend:** Directly binds to PyTorch tensors via `pybind11` without unnecessary memory copies.
|
|
42
|
+
- **Full Autograd Support:** Custom C++ forward and backward passes (`torch::autograd::Function`) for seamless end-to-end training.
|
|
43
|
+
- **Multi-Threaded CPU Execution:** Parallelized with OpenMP and compiled with `-O3 -march=native -ffast-math` for maximum SIMD throughput on CPU.
|
|
44
|
+
- **Custom CUDA Kernels:** Optional hardware-accelerated GPU kernels for high-throughput training and inference.
|
|
45
|
+
- **Multi-Precision Dispatch:** Native support for `float32`, `float16`, and `bfloat16` tensors.
|
|
46
|
+
- **KV-Cache & GQA Ready:** Built-in `seq_offset` support for single-token autoregressive decoding and `forward_qk` for Grouped-Query Attention (GQA).
|
|
47
|
+
|
|
48
|
+
---
|
|
49
|
+
|
|
50
|
+
## 📦 Installation
|
|
51
|
+
|
|
52
|
+
### 1. Install via PyPI (Recommended)
|
|
53
|
+
|
|
54
|
+
You can install `torch-tools` directly using `pip`:
|
|
55
|
+
|
|
56
|
+
```bash
|
|
57
|
+
pip install torch-tools
|
|
58
|
+
```
|
|
59
|
+
|
|
60
|
+
### 2. Install from Source
|
|
61
|
+
|
|
62
|
+
Ensure you have `torch>=2.0`, a C++20 compatible compiler (`gcc>=11` or `clang`), and `cmake>=3.18` installed on your system.
|
|
63
|
+
|
|
64
|
+
**CPU-Only Build:**
|
|
65
|
+
```bash
|
|
66
|
+
git clone https://github.com/ANSH-ind/torch-friend.git
|
|
67
|
+
cd torch-friend
|
|
68
|
+
pip install . --no-build-isolation
|
|
69
|
+
```
|
|
70
|
+
|
|
71
|
+
**CUDA-Enabled Build (for NVIDIA GPUs):**
|
|
72
|
+
```bash
|
|
73
|
+
git clone https://github.com/ANSH-ind/torch-friend.git
|
|
74
|
+
cd torch-friend
|
|
75
|
+
USE_CUDA=ON pip install . --no-build-isolation
|
|
76
|
+
```
|
|
77
|
+
|
|
78
|
+
**Editable Development Install:**
|
|
79
|
+
```bash
|
|
80
|
+
pip install -e . --no-build-isolation
|
|
81
|
+
```
|
|
82
|
+
|
|
83
|
+
---
|
|
84
|
+
|
|
85
|
+
## 🧮 Mathematical Formulation (RoPE)
|
|
86
|
+
|
|
87
|
+
For a given head dimension $d$ and token position $m$, Rotary Position Embedding pairs adjacent feature coordinates $(x_{2i}, x_{2i+1})$ for $i \in \{0, 1, \dots, d/2 - 1\}$ and applies a 2D rotation in the complex plane with frequency $\theta_i = \text{base}^{-2i/d}$:
|
|
88
|
+
|
|
89
|
+
$$
|
|
90
|
+
\begin{pmatrix}
|
|
91
|
+
\tilde{x}_{m, 2i} \\
|
|
92
|
+
\tilde{x}_{m, 2i+1}
|
|
93
|
+
\end{pmatrix}
|
|
94
|
+
=
|
|
95
|
+
\begin{pmatrix}
|
|
96
|
+
\cos(m\theta_i) & -\sin(m\theta_i) \\
|
|
97
|
+
\sin(m\theta_i) & \cos(m\theta_i)
|
|
98
|
+
\end{pmatrix}
|
|
99
|
+
\begin{pmatrix}
|
|
100
|
+
x_{m, 2i} \\
|
|
101
|
+
x_{m, 2i+1}
|
|
102
|
+
\end{pmatrix}
|
|
103
|
+
$$
|
|
104
|
+
|
|
105
|
+
During the backward pass, the exact analytical gradient with respect to the input is computed by applying the transpose (inverse) rotation by $-m\theta_i$:
|
|
106
|
+
|
|
107
|
+
$$
|
|
108
|
+
\begin{pmatrix}
|
|
109
|
+
\frac{\partial \mathcal{L}}{\partial x_{m, 2i}} \\
|
|
110
|
+
\frac{\partial \mathcal{L}}{\partial x_{m, 2i+1}}
|
|
111
|
+
\end{pmatrix}
|
|
112
|
+
=
|
|
113
|
+
\begin{pmatrix}
|
|
114
|
+
\cos(m\theta_i) & \sin(m\theta_i) \\
|
|
115
|
+
-\sin(m\theta_i) & \cos(m\theta_i)
|
|
116
|
+
\end{pmatrix}
|
|
117
|
+
\begin{pmatrix}
|
|
118
|
+
\frac{\partial \mathcal{L}}{\partial \tilde{x}_{m, 2i}} \\
|
|
119
|
+
\frac{\partial \mathcal{L}}{\partial \tilde{x}_{m, 2i+1}}
|
|
120
|
+
\end{pmatrix}
|
|
121
|
+
$$
|
|
122
|
+
|
|
123
|
+
---
|
|
124
|
+
|
|
125
|
+
## 🚀 Usage Guide
|
|
126
|
+
|
|
127
|
+
### 1. Standard `nn.Module` Interface (`RotaryEmbedding`)
|
|
128
|
+
|
|
129
|
+
`RotaryEmbedding` is a drop-in `torch.nn.Module` that automatically computes, caches, and dynamically extends cosine and sine tables across devices and data types.
|
|
130
|
+
|
|
131
|
+
```python
|
|
132
|
+
import torch
|
|
133
|
+
from torch_tools import RotaryEmbedding
|
|
134
|
+
|
|
135
|
+
# Initialize RoPE (head_dim must be an even integer)
|
|
136
|
+
rope = RotaryEmbedding(
|
|
137
|
+
head_dim=64,
|
|
138
|
+
max_seq_len=4096,
|
|
139
|
+
base=10000.0,
|
|
140
|
+
seq_dim=1, # Use 1 for [B, S, H, D] layout, or 2 for [B, H, S, D] layout
|
|
141
|
+
)
|
|
142
|
+
|
|
143
|
+
# Input tensor: [Batch=2, SeqLen=128, Heads=8, HeadDim=64]
|
|
144
|
+
x = torch.randn(2, 128, 8, 64, requires_grad=True)
|
|
145
|
+
|
|
146
|
+
# Forward pass (C++ / CUDA kernel)
|
|
147
|
+
out = rope(x)
|
|
148
|
+
|
|
149
|
+
# Backward pass (C++ custom autograd engine)
|
|
150
|
+
loss = out.sum()
|
|
151
|
+
loss.backward()
|
|
152
|
+
|
|
153
|
+
print("Module:", rope)
|
|
154
|
+
print("Output shape:", out.shape)
|
|
155
|
+
print("Input gradient norm:", x.grad.norm().item())
|
|
156
|
+
```
|
|
157
|
+
|
|
158
|
+
### 2. Simultaneous Query & Key Rotation (`forward_qk`)
|
|
159
|
+
|
|
160
|
+
In Transformer attention layers (including Multi-Head Attention and Grouped-Query Attention where Query and Key head counts differ), use `forward_qk` to rotate both tensors cleanly:
|
|
161
|
+
|
|
162
|
+
```python
|
|
163
|
+
import torch
|
|
164
|
+
from torch_tools import RotaryEmbedding
|
|
165
|
+
|
|
166
|
+
rope = RotaryEmbedding(head_dim=64, max_seq_len=4096, seq_dim=1)
|
|
167
|
+
|
|
168
|
+
# Grouped-Query Attention (GQA): 8 Query heads, 2 Key/Value heads
|
|
169
|
+
q = torch.randn(2, 64, 8, 64, requires_grad=True)
|
|
170
|
+
k = torch.randn(2, 64, 2, 64, requires_grad=True)
|
|
171
|
+
|
|
172
|
+
q_rot, k_rot = rope.forward_qk(q, k)
|
|
173
|
+
|
|
174
|
+
print("Rotated Q shape:", q_rot.shape)
|
|
175
|
+
print("Rotated K shape:", k_rot.shape)
|
|
176
|
+
```
|
|
177
|
+
|
|
178
|
+
### 3. Autoregressive Decoding with `seq_offset` (KV-Cache)
|
|
179
|
+
|
|
180
|
+
When generating tokens one-by-one during inference with a KV-cache, pass `seq_offset` so the newly generated token is rotated using its exact absolute position in the sequence:
|
|
181
|
+
|
|
182
|
+
```python
|
|
183
|
+
import torch
|
|
184
|
+
from torch_tools import RotaryEmbedding
|
|
185
|
+
|
|
186
|
+
rope = RotaryEmbedding(head_dim=64, max_seq_len=4096, seq_dim=1)
|
|
187
|
+
|
|
188
|
+
# Prefill phase: 128 prompt tokens (positions 0..127)
|
|
189
|
+
prompt_q = torch.randn(2, 128, 8, 64)
|
|
190
|
+
prompt_q_rot = rope(prompt_q, seq_offset=0)
|
|
191
|
+
|
|
192
|
+
# Decode step: 1 new token at position 128
|
|
193
|
+
next_token_q = torch.randn(2, 1, 8, 64)
|
|
194
|
+
next_token_q_rot = rope(next_token_q, seq_offset=128)
|
|
195
|
+
```
|
|
196
|
+
|
|
197
|
+
### 4. Stateless Functional API (`apply_rope`)
|
|
198
|
+
|
|
199
|
+
If you manage your own custom precomputed `cos` and `sin` frequency caches (e.g., for YaRN, NTK-aware scaling, or custom position IDs) of shape $[S, d/2]$, use `apply_rope`:
|
|
200
|
+
|
|
201
|
+
```python
|
|
202
|
+
import torch
|
|
203
|
+
from torch_tools import apply_rope
|
|
204
|
+
|
|
205
|
+
batch, seq_len, heads, head_dim = 2, 32, 4, 64
|
|
206
|
+
x = torch.randn(batch, seq_len, heads, head_dim, requires_grad=True)
|
|
207
|
+
|
|
208
|
+
# Precomputed cos and sin tables of shape [seq_len, head_dim // 2]
|
|
209
|
+
cos = torch.ones(seq_len, head_dim // 2)
|
|
210
|
+
sin = torch.zeros(seq_len, head_dim // 2)
|
|
211
|
+
|
|
212
|
+
out = apply_rope(x, cos, sin, seq_dim=1)
|
|
213
|
+
out.sum().backward()
|
|
214
|
+
```
|
|
215
|
+
|
|
216
|
+
---
|
|
217
|
+
|
|
218
|
+
## 🗺️ Roadmap: Upcoming Tools in `torch-tools`
|
|
219
|
+
|
|
220
|
+
`torch-tools` is designed to be a complete, high-speed C++/CUDA operator suite for PyTorch. While **RoPE** is our first completed module, several new operators are currently under development and will be released in upcoming versions:
|
|
221
|
+
|
|
222
|
+
- [x] **Rotary Position Embedding (RoPE)** — *Completed & Production-Ready (CPU OpenMP + CUDA, Custom Autograd, GQA & KV-Cache support)*
|
|
223
|
+
- [ ] **Fused RMSNorm** — *Ultra-fast Root Mean Square Layer Normalization with fused residual addition in C++/CUDA*
|
|
224
|
+
- [ ] **Fused SwiGLU / GeGLU Activations** — *Memory-efficient gated linear unit kernels with custom backward passes*
|
|
225
|
+
- [ ] **Grouped-Query Attention (GQA) Utilities** — *Zero-copy KV head broadcasting and fused attention helpers*
|
|
226
|
+
- [ ] **Low-Bit & Ternary Quantization Kernels** — *High-speed bit-packed linear operations for efficient LLM inference*
|
|
227
|
+
- [ ] **Fused Cross-Entropy Loss** — *Memory-saving logits-to-loss C++/CUDA computation*
|
|
228
|
+
|
|
229
|
+
---
|
|
230
|
+
|
|
231
|
+
## 🛠️ Building Distributable Wheels Locally
|
|
232
|
+
|
|
233
|
+
To build a standalone `.whl` package inside the `dist/` folder for deployment or uploading to PyPI via `twine`:
|
|
234
|
+
|
|
235
|
+
```bash
|
|
236
|
+
pip wheel . --no-deps --no-build-isolation -w dist/
|
|
237
|
+
```
|
|
238
|
+
|
|
239
|
+
---
|
|
240
|
+
|
|
241
|
+
## 👤 Author & License
|
|
242
|
+
|
|
243
|
+
- **Author:** Ansh Raj ([@ANSH-ind](https://github.com/ANSH-ind))
|
|
244
|
+
- **Contact:** anshraj0000000001@gmail.com
|
|
245
|
+
- **Copyright:** © 2026 Techgears - All Rights Reserved.
|
|
246
|
+
- **License:** Released under the [MIT License](LICENSE).
|
|
@@ -0,0 +1,223 @@
|
|
|
1
|
+
# ⚡ torch-tools
|
|
2
|
+
|
|
3
|
+
**High-Performance C++20, OpenMP, and CUDA Extensions for PyTorch**
|
|
4
|
+
|
|
5
|
+
[](https://pypi.org/project/torch-tools/)
|
|
6
|
+
[](https://en.cppreference.com/w/cpp/20)
|
|
7
|
+
[](https://pytorch.org/)
|
|
8
|
+
[](https://opensource.org/licenses/MIT)
|
|
9
|
+
|
|
10
|
+
`torch-tools` is a native C++/LibTorch operator library built to accelerate modern Deep Learning and Transformer workloads in PyTorch. Instead of relying on memory-bound Python operations, `torch-tools` executes fused kernels directly in C++20 (using OpenMP multithreading and SIMD vectorization on CPU) and custom CUDA kernels on NVIDIA GPUs.
|
|
11
|
+
|
|
12
|
+
> **📢 Project Status:** **Rotary Position Embedding (RoPE)** is 100% complete, tested, and production-ready! `torch-tools` is an actively growing ecosystem—many more custom C++/CUDA neural network primitives, fused normalization layers, and PyTorch utilities are on the way.
|
|
13
|
+
|
|
14
|
+
---
|
|
15
|
+
|
|
16
|
+
## ✨ Key Highlights
|
|
17
|
+
|
|
18
|
+
- **Zero-Overhead C++20 & LibTorch Backend:** Directly binds to PyTorch tensors via `pybind11` without unnecessary memory copies.
|
|
19
|
+
- **Full Autograd Support:** Custom C++ forward and backward passes (`torch::autograd::Function`) for seamless end-to-end training.
|
|
20
|
+
- **Multi-Threaded CPU Execution:** Parallelized with OpenMP and compiled with `-O3 -march=native -ffast-math` for maximum SIMD throughput on CPU.
|
|
21
|
+
- **Custom CUDA Kernels:** Optional hardware-accelerated GPU kernels for high-throughput training and inference.
|
|
22
|
+
- **Multi-Precision Dispatch:** Native support for `float32`, `float16`, and `bfloat16` tensors.
|
|
23
|
+
- **KV-Cache & GQA Ready:** Built-in `seq_offset` support for single-token autoregressive decoding and `forward_qk` for Grouped-Query Attention (GQA).
|
|
24
|
+
|
|
25
|
+
---
|
|
26
|
+
|
|
27
|
+
## 📦 Installation
|
|
28
|
+
|
|
29
|
+
### 1. Install via PyPI (Recommended)
|
|
30
|
+
|
|
31
|
+
You can install `torch-tools` directly using `pip`:
|
|
32
|
+
|
|
33
|
+
```bash
|
|
34
|
+
pip install torch-tools
|
|
35
|
+
```
|
|
36
|
+
|
|
37
|
+
### 2. Install from Source
|
|
38
|
+
|
|
39
|
+
Ensure you have `torch>=2.0`, a C++20 compatible compiler (`gcc>=11` or `clang`), and `cmake>=3.18` installed on your system.
|
|
40
|
+
|
|
41
|
+
**CPU-Only Build:**
|
|
42
|
+
```bash
|
|
43
|
+
git clone https://github.com/ANSH-ind/torch-friend.git
|
|
44
|
+
cd torch-friend
|
|
45
|
+
pip install . --no-build-isolation
|
|
46
|
+
```
|
|
47
|
+
|
|
48
|
+
**CUDA-Enabled Build (for NVIDIA GPUs):**
|
|
49
|
+
```bash
|
|
50
|
+
git clone https://github.com/ANSH-ind/torch-friend.git
|
|
51
|
+
cd torch-friend
|
|
52
|
+
USE_CUDA=ON pip install . --no-build-isolation
|
|
53
|
+
```
|
|
54
|
+
|
|
55
|
+
**Editable Development Install:**
|
|
56
|
+
```bash
|
|
57
|
+
pip install -e . --no-build-isolation
|
|
58
|
+
```
|
|
59
|
+
|
|
60
|
+
---
|
|
61
|
+
|
|
62
|
+
## 🧮 Mathematical Formulation (RoPE)
|
|
63
|
+
|
|
64
|
+
For a given head dimension $d$ and token position $m$, Rotary Position Embedding pairs adjacent feature coordinates $(x_{2i}, x_{2i+1})$ for $i \in \{0, 1, \dots, d/2 - 1\}$ and applies a 2D rotation in the complex plane with frequency $\theta_i = \text{base}^{-2i/d}$:
|
|
65
|
+
|
|
66
|
+
$$
|
|
67
|
+
\begin{pmatrix}
|
|
68
|
+
\tilde{x}_{m, 2i} \\
|
|
69
|
+
\tilde{x}_{m, 2i+1}
|
|
70
|
+
\end{pmatrix}
|
|
71
|
+
=
|
|
72
|
+
\begin{pmatrix}
|
|
73
|
+
\cos(m\theta_i) & -\sin(m\theta_i) \\
|
|
74
|
+
\sin(m\theta_i) & \cos(m\theta_i)
|
|
75
|
+
\end{pmatrix}
|
|
76
|
+
\begin{pmatrix}
|
|
77
|
+
x_{m, 2i} \\
|
|
78
|
+
x_{m, 2i+1}
|
|
79
|
+
\end{pmatrix}
|
|
80
|
+
$$
|
|
81
|
+
|
|
82
|
+
During the backward pass, the exact analytical gradient with respect to the input is computed by applying the transpose (inverse) rotation by $-m\theta_i$:
|
|
83
|
+
|
|
84
|
+
$$
|
|
85
|
+
\begin{pmatrix}
|
|
86
|
+
\frac{\partial \mathcal{L}}{\partial x_{m, 2i}} \\
|
|
87
|
+
\frac{\partial \mathcal{L}}{\partial x_{m, 2i+1}}
|
|
88
|
+
\end{pmatrix}
|
|
89
|
+
=
|
|
90
|
+
\begin{pmatrix}
|
|
91
|
+
\cos(m\theta_i) & \sin(m\theta_i) \\
|
|
92
|
+
-\sin(m\theta_i) & \cos(m\theta_i)
|
|
93
|
+
\end{pmatrix}
|
|
94
|
+
\begin{pmatrix}
|
|
95
|
+
\frac{\partial \mathcal{L}}{\partial \tilde{x}_{m, 2i}} \\
|
|
96
|
+
\frac{\partial \mathcal{L}}{\partial \tilde{x}_{m, 2i+1}}
|
|
97
|
+
\end{pmatrix}
|
|
98
|
+
$$
|
|
99
|
+
|
|
100
|
+
---
|
|
101
|
+
|
|
102
|
+
## 🚀 Usage Guide
|
|
103
|
+
|
|
104
|
+
### 1. Standard `nn.Module` Interface (`RotaryEmbedding`)
|
|
105
|
+
|
|
106
|
+
`RotaryEmbedding` is a drop-in `torch.nn.Module` that automatically computes, caches, and dynamically extends cosine and sine tables across devices and data types.
|
|
107
|
+
|
|
108
|
+
```python
|
|
109
|
+
import torch
|
|
110
|
+
from torch_tools import RotaryEmbedding
|
|
111
|
+
|
|
112
|
+
# Initialize RoPE (head_dim must be an even integer)
|
|
113
|
+
rope = RotaryEmbedding(
|
|
114
|
+
head_dim=64,
|
|
115
|
+
max_seq_len=4096,
|
|
116
|
+
base=10000.0,
|
|
117
|
+
seq_dim=1, # Use 1 for [B, S, H, D] layout, or 2 for [B, H, S, D] layout
|
|
118
|
+
)
|
|
119
|
+
|
|
120
|
+
# Input tensor: [Batch=2, SeqLen=128, Heads=8, HeadDim=64]
|
|
121
|
+
x = torch.randn(2, 128, 8, 64, requires_grad=True)
|
|
122
|
+
|
|
123
|
+
# Forward pass (C++ / CUDA kernel)
|
|
124
|
+
out = rope(x)
|
|
125
|
+
|
|
126
|
+
# Backward pass (C++ custom autograd engine)
|
|
127
|
+
loss = out.sum()
|
|
128
|
+
loss.backward()
|
|
129
|
+
|
|
130
|
+
print("Module:", rope)
|
|
131
|
+
print("Output shape:", out.shape)
|
|
132
|
+
print("Input gradient norm:", x.grad.norm().item())
|
|
133
|
+
```
|
|
134
|
+
|
|
135
|
+
### 2. Simultaneous Query & Key Rotation (`forward_qk`)
|
|
136
|
+
|
|
137
|
+
In Transformer attention layers (including Multi-Head Attention and Grouped-Query Attention where Query and Key head counts differ), use `forward_qk` to rotate both tensors cleanly:
|
|
138
|
+
|
|
139
|
+
```python
|
|
140
|
+
import torch
|
|
141
|
+
from torch_tools import RotaryEmbedding
|
|
142
|
+
|
|
143
|
+
rope = RotaryEmbedding(head_dim=64, max_seq_len=4096, seq_dim=1)
|
|
144
|
+
|
|
145
|
+
# Grouped-Query Attention (GQA): 8 Query heads, 2 Key/Value heads
|
|
146
|
+
q = torch.randn(2, 64, 8, 64, requires_grad=True)
|
|
147
|
+
k = torch.randn(2, 64, 2, 64, requires_grad=True)
|
|
148
|
+
|
|
149
|
+
q_rot, k_rot = rope.forward_qk(q, k)
|
|
150
|
+
|
|
151
|
+
print("Rotated Q shape:", q_rot.shape)
|
|
152
|
+
print("Rotated K shape:", k_rot.shape)
|
|
153
|
+
```
|
|
154
|
+
|
|
155
|
+
### 3. Autoregressive Decoding with `seq_offset` (KV-Cache)
|
|
156
|
+
|
|
157
|
+
When generating tokens one-by-one during inference with a KV-cache, pass `seq_offset` so the newly generated token is rotated using its exact absolute position in the sequence:
|
|
158
|
+
|
|
159
|
+
```python
|
|
160
|
+
import torch
|
|
161
|
+
from torch_tools import RotaryEmbedding
|
|
162
|
+
|
|
163
|
+
rope = RotaryEmbedding(head_dim=64, max_seq_len=4096, seq_dim=1)
|
|
164
|
+
|
|
165
|
+
# Prefill phase: 128 prompt tokens (positions 0..127)
|
|
166
|
+
prompt_q = torch.randn(2, 128, 8, 64)
|
|
167
|
+
prompt_q_rot = rope(prompt_q, seq_offset=0)
|
|
168
|
+
|
|
169
|
+
# Decode step: 1 new token at position 128
|
|
170
|
+
next_token_q = torch.randn(2, 1, 8, 64)
|
|
171
|
+
next_token_q_rot = rope(next_token_q, seq_offset=128)
|
|
172
|
+
```
|
|
173
|
+
|
|
174
|
+
### 4. Stateless Functional API (`apply_rope`)
|
|
175
|
+
|
|
176
|
+
If you manage your own custom precomputed `cos` and `sin` frequency caches (e.g., for YaRN, NTK-aware scaling, or custom position IDs) of shape $[S, d/2]$, use `apply_rope`:
|
|
177
|
+
|
|
178
|
+
```python
|
|
179
|
+
import torch
|
|
180
|
+
from torch_tools import apply_rope
|
|
181
|
+
|
|
182
|
+
batch, seq_len, heads, head_dim = 2, 32, 4, 64
|
|
183
|
+
x = torch.randn(batch, seq_len, heads, head_dim, requires_grad=True)
|
|
184
|
+
|
|
185
|
+
# Precomputed cos and sin tables of shape [seq_len, head_dim // 2]
|
|
186
|
+
cos = torch.ones(seq_len, head_dim // 2)
|
|
187
|
+
sin = torch.zeros(seq_len, head_dim // 2)
|
|
188
|
+
|
|
189
|
+
out = apply_rope(x, cos, sin, seq_dim=1)
|
|
190
|
+
out.sum().backward()
|
|
191
|
+
```
|
|
192
|
+
|
|
193
|
+
---
|
|
194
|
+
|
|
195
|
+
## 🗺️ Roadmap: Upcoming Tools in `torch-tools`
|
|
196
|
+
|
|
197
|
+
`torch-tools` is designed to be a complete, high-speed C++/CUDA operator suite for PyTorch. While **RoPE** is our first completed module, several new operators are currently under development and will be released in upcoming versions:
|
|
198
|
+
|
|
199
|
+
- [x] **Rotary Position Embedding (RoPE)** — *Completed & Production-Ready (CPU OpenMP + CUDA, Custom Autograd, GQA & KV-Cache support)*
|
|
200
|
+
- [ ] **Fused RMSNorm** — *Ultra-fast Root Mean Square Layer Normalization with fused residual addition in C++/CUDA*
|
|
201
|
+
- [ ] **Fused SwiGLU / GeGLU Activations** — *Memory-efficient gated linear unit kernels with custom backward passes*
|
|
202
|
+
- [ ] **Grouped-Query Attention (GQA) Utilities** — *Zero-copy KV head broadcasting and fused attention helpers*
|
|
203
|
+
- [ ] **Low-Bit & Ternary Quantization Kernels** — *High-speed bit-packed linear operations for efficient LLM inference*
|
|
204
|
+
- [ ] **Fused Cross-Entropy Loss** — *Memory-saving logits-to-loss C++/CUDA computation*
|
|
205
|
+
|
|
206
|
+
---
|
|
207
|
+
|
|
208
|
+
## 🛠️ Building Distributable Wheels Locally
|
|
209
|
+
|
|
210
|
+
To build a standalone `.whl` package inside the `dist/` folder for deployment or uploading to PyPI via `twine`:
|
|
211
|
+
|
|
212
|
+
```bash
|
|
213
|
+
pip wheel . --no-deps --no-build-isolation -w dist/
|
|
214
|
+
```
|
|
215
|
+
|
|
216
|
+
---
|
|
217
|
+
|
|
218
|
+
## 👤 Author & License
|
|
219
|
+
|
|
220
|
+
- **Author:** Ansh Raj ([@ANSH-ind](https://github.com/ANSH-ind))
|
|
221
|
+
- **Contact:** anshraj0000000001@gmail.com
|
|
222
|
+
- **Copyright:** © 2026 Techgears - All Rights Reserved.
|
|
223
|
+
- **License:** Released under the [MIT License](LICENSE).
|
|
@@ -0,0 +1,75 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @file bind.cpp
|
|
3
|
+
* @brief Pybind11 Python bindings for torch_tools (RoPE module and functions).
|
|
4
|
+
* @author Ansh Raj
|
|
5
|
+
* @version 1.0.1
|
|
6
|
+
* @date 2026
|
|
7
|
+
*/
|
|
8
|
+
|
|
9
|
+
#include <torch/extension.h>
|
|
10
|
+
#include <torch/torch.h>
|
|
11
|
+
#include "torch_tools/rope.hpp"
|
|
12
|
+
|
|
13
|
+
PYBIND11_MODULE(TORCH_EXTENSION_NAME, m) {
|
|
14
|
+
m.doc() = "Ultra-optimized C++ / LibTorch implementations of Rotary Position Embedding (RoPE)";
|
|
15
|
+
|
|
16
|
+
// Bind RotaryEmbeddingOptions struct using explicit lambdas to avoid overloaded method ambiguity
|
|
17
|
+
py::class_<torch_tools::RotaryEmbeddingOptions>(m, "RotaryEmbeddingOptions")
|
|
18
|
+
.def(py::init<int64_t>(), py::arg("head_dim"))
|
|
19
|
+
.def_property("head_dim",
|
|
20
|
+
[](const torch_tools::RotaryEmbeddingOptions& self) { return self.head_dim(); },
|
|
21
|
+
[](torch_tools::RotaryEmbeddingOptions& self, int64_t val) { self.head_dim(val); })
|
|
22
|
+
.def_property("max_seq_len",
|
|
23
|
+
[](const torch_tools::RotaryEmbeddingOptions& self) { return self.max_seq_len(); },
|
|
24
|
+
[](torch_tools::RotaryEmbeddingOptions& self, int64_t val) { self.max_seq_len(val); })
|
|
25
|
+
.def_property("base",
|
|
26
|
+
[](const torch_tools::RotaryEmbeddingOptions& self) { return self.base(); },
|
|
27
|
+
[](torch_tools::RotaryEmbeddingOptions& self, double val) { self.base(val); })
|
|
28
|
+
.def_property("seq_dim",
|
|
29
|
+
[](const torch_tools::RotaryEmbeddingOptions& self) { return self.seq_dim(); },
|
|
30
|
+
[](torch_tools::RotaryEmbeddingOptions& self, int64_t val) { self.seq_dim(val); });
|
|
31
|
+
|
|
32
|
+
// Bind RotaryEmbeddingImpl Module
|
|
33
|
+
py::class_<torch_tools::RotaryEmbeddingImpl, std::shared_ptr<torch_tools::RotaryEmbeddingImpl>>(m, "RotaryEmbeddingImpl")
|
|
34
|
+
.def(py::init<int64_t, int64_t, double, int64_t>(),
|
|
35
|
+
py::arg("head_dim"),
|
|
36
|
+
py::arg("max_seq_len") = 4096,
|
|
37
|
+
py::arg("base") = 10000.0,
|
|
38
|
+
py::arg("seq_dim") = 1)
|
|
39
|
+
.def("forward", &torch_tools::RotaryEmbeddingImpl::forward,
|
|
40
|
+
py::arg("x"),
|
|
41
|
+
py::arg("seq_offset") = 0)
|
|
42
|
+
.def("forward_qk", &torch_tools::RotaryEmbeddingImpl::forward_qk,
|
|
43
|
+
py::arg("q"),
|
|
44
|
+
py::arg("k"),
|
|
45
|
+
py::arg("seq_offset") = 0)
|
|
46
|
+
.def("update_cos_sin_cache", &torch_tools::RotaryEmbeddingImpl::update_cos_sin_cache,
|
|
47
|
+
py::arg("seq_len"),
|
|
48
|
+
py::arg("device"),
|
|
49
|
+
py::arg("dtype"))
|
|
50
|
+
.def_readwrite("options", &torch_tools::RotaryEmbeddingImpl::options);
|
|
51
|
+
|
|
52
|
+
// Bind RotaryEmbedding ModuleHolder wrapper
|
|
53
|
+
py::class_<torch_tools::RotaryEmbedding>(m, "RotaryEmbedding")
|
|
54
|
+
.def(py::init<int64_t, int64_t, double, int64_t>(),
|
|
55
|
+
py::arg("head_dim"),
|
|
56
|
+
py::arg("max_seq_len") = 4096,
|
|
57
|
+
py::arg("base") = 10000.0,
|
|
58
|
+
py::arg("seq_dim") = 1)
|
|
59
|
+
.def("__call__", [](torch_tools::RotaryEmbedding& self, const torch::Tensor& x, int64_t seq_offset) {
|
|
60
|
+
return self->forward(x, seq_offset);
|
|
61
|
+
}, py::arg("x"), py::arg("seq_offset") = 0)
|
|
62
|
+
.def("forward", [](torch_tools::RotaryEmbedding& self, const torch::Tensor& x, int64_t seq_offset) {
|
|
63
|
+
return self->forward(x, seq_offset);
|
|
64
|
+
}, py::arg("x"), py::arg("seq_offset") = 0)
|
|
65
|
+
.def("forward_qk", [](torch_tools::RotaryEmbedding& self, const torch::Tensor& q, const torch::Tensor& k, int64_t seq_offset) {
|
|
66
|
+
return self->forward_qk(q, k, seq_offset);
|
|
67
|
+
}, py::arg("q"), py::arg("k"), py::arg("seq_offset") = 0);
|
|
68
|
+
|
|
69
|
+
// Expose functional apply_rope interface
|
|
70
|
+
m.def("apply_rope", &torch_tools::apply_rope,
|
|
71
|
+
py::arg("x"),
|
|
72
|
+
py::arg("cos"),
|
|
73
|
+
py::arg("sin"),
|
|
74
|
+
py::arg("seq_dim") = 1);
|
|
75
|
+
}
|