adafactor8bit 0.1.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.
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 WANG YAN
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1,3 @@
1
+ include LICENSE
2
+ include README.md
3
+ recursive-include adafactor8bit *.cu
@@ -0,0 +1,117 @@
1
+ Metadata-Version: 2.4
2
+ Name: adafactor8bit
3
+ Version: 0.1.0
4
+ Summary: 8-bit Adafactor Optimizer with Fused CUDA Kernels
5
+ Home-page: https://github.com/yanfeiwong/adafactor-8bit
6
+ Author: WANG YAN
7
+ Author-email: yanfeiwong1997@outlook.com
8
+ Classifier: Programming Language :: Python :: 3
9
+ Classifier: License :: OSI Approved :: MIT License
10
+ Classifier: Operating System :: OS Independent
11
+ Classifier: Topic :: Scientific/Engineering :: Artificial Intelligence
12
+ Requires-Python: >=3.10
13
+ Description-Content-Type: text/markdown
14
+ License-File: LICENSE
15
+ Requires-Dist: torch>=2.1
16
+ Requires-Dist: ninja
17
+ Dynamic: author
18
+ Dynamic: author-email
19
+ Dynamic: classifier
20
+ Dynamic: description
21
+ Dynamic: description-content-type
22
+ Dynamic: home-page
23
+ Dynamic: license-file
24
+ Dynamic: requires-dist
25
+ Dynamic: requires-python
26
+ Dynamic: summary
27
+
28
+ **English** | [中文](./README_ZH.md)
29
+
30
+ # Adafactor 8-bit with Fused CUDA Kernels
31
+
32
+ An 8-bit Adafactor optimizer designed for memory-efficient large-scale model training.
33
+
34
+ It uses fused CUDA kernels and block-wise quantization to reduce optimizer state memory while maintaining training stability, making it suitable for training large models such as LLMs and diffusion models.
35
+
36
+ ## Key Features
37
+
38
+ - **Fused CUDA Kernel**: Integrates dequantization, EMA updates, Warp-Shuffle reduction, and requantization into a single kernel, utilizing `float4` vectorization to maximize memory bandwidth utilization.
39
+ - **Zero CPU-GPU Sync**: Refactored the control flow to eliminate implicit synchronizations, ensuring the GPU computation pipeline runs asynchronously at high speed.
40
+ - **Cross-Platform JIT**: Utilizes JIT (Just-In-Time) automatic compilation for seamless setup across Windows and Linux environments.
41
+
42
+ ## Algorithm Details
43
+
44
+ Rebuilt upon the official PyTorch Adafactor, the mathematical logic **aligns more closely with the original paper and `HuggingFace transformers`**. Key differences include:
45
+
46
+ 1. **Safe Injection of `eps1`**: The official PyTorch implementation defaults to `eps1=None` and relies on `clamp`, which can lead to NaNs when encountering zero or extremely small gradients. This project adopts the original `grad_squared + eps1` approach, fundamentally guaranteeing the strict positive definiteness of the second moment and preventing training crashes caused by `rsqrt(0)`.
47
+ 2. **Coupled Weight Decay**: Unlike the official PyTorch implementation which decouples Weight Decay from RMS, this project retains the Coupled mechanism from the original paper (Weight Decay multiplied by the effective learning rate that includes RMS scaling).
48
+ 3. **Standard Parameter Support**: Fully retains core Adafactor switches such as `relative_step` and `scale_parameter`, ensuring compatibility with existing learning rate scheduling strategies.
49
+
50
+ ## Performance
51
+
52
+ - **Memory Footprint**: The memory usage of optimizer states is **significantly lower than `AdamW8Bit`** (bitsandbytes), making it an ideal choice for training massive models or when memory-constrained.
53
+ - **Training Speed**: The Fused Kernel and Zero-Sync design enable it to achieve step speeds comparable to mainstream 8-bit optimizers.
54
+ - **Quantization Precision & Stability**: The second moment (variance) in Adafactor is always non-negative, so we map it to `UINT8 (0~255)`. Compared to traditional 8-bit optimizers that map to `INT8 (-127~127)`, providing higher effective quantization precision within the non-negative variance domain.
55
+
56
+ ## Installation
57
+
58
+ This project uses JIT (Just-In-Time) compilation.
59
+
60
+ Please ensure torch and ninja are installed, and a CUDA compiler (such as MSVC or GCC) is available in your environment.
61
+
62
+ If CUDA compilation fails, the optimizer will automatically fall back to the pure PyTorch implementation.
63
+
64
+
65
+ ```bash
66
+ pip install git+https://github.com/yanfeiwong/adafactor-8bit.git
67
+ ```
68
+
69
+ ## Usage Example
70
+
71
+ It is recommended to use `param_groups` to keep sensitive layers (Embedding, Norm, Bias) in FP32, enabling 8-bit quantization only for large 2D weight matrices.
72
+
73
+ ```python
74
+ import torch
75
+ import torch.nn as nn
76
+ from adafactor8bit import Adafactor8Bit
77
+
78
+ def get_param_groups(model, weight_decay=1e-2):
79
+ decay, no_decay = [], []
80
+ for name, param in model.named_parameters():
81
+ if not param.requires_grad: continue
82
+ # Protect 1D tensors, biases, norms, and embeddings
83
+ if param.ndim <= 1 or "bias" in name or "norm" in name or "embed" in name:
84
+ no_decay.append(param)
85
+ else:
86
+ decay.append(param)
87
+
88
+ return [
89
+ {"params": decay, "weight_decay": weight_decay, "quantize": True},
90
+ {"params": no_decay, "weight_decay": 0.0, "quantize": False}
91
+ ]
92
+
93
+ model = MyModel().cuda()
94
+ optimizer = Adafactor8Bit(
95
+ get_param_groups(model),
96
+ lr=1e-3,
97
+ relative_step=False,
98
+ block_size=2048,
99
+ min_8bit_size=4096
100
+ )
101
+
102
+ # Training loop...
103
+ ```
104
+
105
+ For a complete example, please refer to [basic_usage.py](./examples/basic_usage.py).
106
+
107
+ ## Acknowledgements
108
+
109
+ Thanks to the large language models Qwen and DeepSeek for valuable technical discussions and code reviews on CUDA low-level optimization, memory safety mechanisms, and cross-platform compilation pipeline design.
110
+
111
+ Thanks to Tim Dettmers for the inspiration from the paper [8-BIT OPTIMIZERS VIA BLOCK-WISE QUANTIZATION](https://arxiv.org/pdf/2110.02861) and the [bitsandbytes](https://github.com/bitsandbytes-foundation/bitsandbytes) library.
112
+
113
+ Thanks to the PyTorch team for providing the foundational Optimizer implementation and the C++ Extension toolchain.
114
+
115
+ ## License
116
+
117
+ [The project is released under the MIT License.](./LICENSE)
@@ -0,0 +1,90 @@
1
+ **English** | [中文](./README_ZH.md)
2
+
3
+ # Adafactor 8-bit with Fused CUDA Kernels
4
+
5
+ An 8-bit Adafactor optimizer designed for memory-efficient large-scale model training.
6
+
7
+ It uses fused CUDA kernels and block-wise quantization to reduce optimizer state memory while maintaining training stability, making it suitable for training large models such as LLMs and diffusion models.
8
+
9
+ ## Key Features
10
+
11
+ - **Fused CUDA Kernel**: Integrates dequantization, EMA updates, Warp-Shuffle reduction, and requantization into a single kernel, utilizing `float4` vectorization to maximize memory bandwidth utilization.
12
+ - **Zero CPU-GPU Sync**: Refactored the control flow to eliminate implicit synchronizations, ensuring the GPU computation pipeline runs asynchronously at high speed.
13
+ - **Cross-Platform JIT**: Utilizes JIT (Just-In-Time) automatic compilation for seamless setup across Windows and Linux environments.
14
+
15
+ ## Algorithm Details
16
+
17
+ Rebuilt upon the official PyTorch Adafactor, the mathematical logic **aligns more closely with the original paper and `HuggingFace transformers`**. Key differences include:
18
+
19
+ 1. **Safe Injection of `eps1`**: The official PyTorch implementation defaults to `eps1=None` and relies on `clamp`, which can lead to NaNs when encountering zero or extremely small gradients. This project adopts the original `grad_squared + eps1` approach, fundamentally guaranteeing the strict positive definiteness of the second moment and preventing training crashes caused by `rsqrt(0)`.
20
+ 2. **Coupled Weight Decay**: Unlike the official PyTorch implementation which decouples Weight Decay from RMS, this project retains the Coupled mechanism from the original paper (Weight Decay multiplied by the effective learning rate that includes RMS scaling).
21
+ 3. **Standard Parameter Support**: Fully retains core Adafactor switches such as `relative_step` and `scale_parameter`, ensuring compatibility with existing learning rate scheduling strategies.
22
+
23
+ ## Performance
24
+
25
+ - **Memory Footprint**: The memory usage of optimizer states is **significantly lower than `AdamW8Bit`** (bitsandbytes), making it an ideal choice for training massive models or when memory-constrained.
26
+ - **Training Speed**: The Fused Kernel and Zero-Sync design enable it to achieve step speeds comparable to mainstream 8-bit optimizers.
27
+ - **Quantization Precision & Stability**: The second moment (variance) in Adafactor is always non-negative, so we map it to `UINT8 (0~255)`. Compared to traditional 8-bit optimizers that map to `INT8 (-127~127)`, providing higher effective quantization precision within the non-negative variance domain.
28
+
29
+ ## Installation
30
+
31
+ This project uses JIT (Just-In-Time) compilation.
32
+
33
+ Please ensure torch and ninja are installed, and a CUDA compiler (such as MSVC or GCC) is available in your environment.
34
+
35
+ If CUDA compilation fails, the optimizer will automatically fall back to the pure PyTorch implementation.
36
+
37
+
38
+ ```bash
39
+ pip install git+https://github.com/yanfeiwong/adafactor-8bit.git
40
+ ```
41
+
42
+ ## Usage Example
43
+
44
+ It is recommended to use `param_groups` to keep sensitive layers (Embedding, Norm, Bias) in FP32, enabling 8-bit quantization only for large 2D weight matrices.
45
+
46
+ ```python
47
+ import torch
48
+ import torch.nn as nn
49
+ from adafactor8bit import Adafactor8Bit
50
+
51
+ def get_param_groups(model, weight_decay=1e-2):
52
+ decay, no_decay = [], []
53
+ for name, param in model.named_parameters():
54
+ if not param.requires_grad: continue
55
+ # Protect 1D tensors, biases, norms, and embeddings
56
+ if param.ndim <= 1 or "bias" in name or "norm" in name or "embed" in name:
57
+ no_decay.append(param)
58
+ else:
59
+ decay.append(param)
60
+
61
+ return [
62
+ {"params": decay, "weight_decay": weight_decay, "quantize": True},
63
+ {"params": no_decay, "weight_decay": 0.0, "quantize": False}
64
+ ]
65
+
66
+ model = MyModel().cuda()
67
+ optimizer = Adafactor8Bit(
68
+ get_param_groups(model),
69
+ lr=1e-3,
70
+ relative_step=False,
71
+ block_size=2048,
72
+ min_8bit_size=4096
73
+ )
74
+
75
+ # Training loop...
76
+ ```
77
+
78
+ For a complete example, please refer to [basic_usage.py](./examples/basic_usage.py).
79
+
80
+ ## Acknowledgements
81
+
82
+ Thanks to the large language models Qwen and DeepSeek for valuable technical discussions and code reviews on CUDA low-level optimization, memory safety mechanisms, and cross-platform compilation pipeline design.
83
+
84
+ Thanks to Tim Dettmers for the inspiration from the paper [8-BIT OPTIMIZERS VIA BLOCK-WISE QUANTIZATION](https://arxiv.org/pdf/2110.02861) and the [bitsandbytes](https://github.com/bitsandbytes-foundation/bitsandbytes) library.
85
+
86
+ Thanks to the PyTorch team for providing the foundational Optimizer implementation and the C++ Extension toolchain.
87
+
88
+ ## License
89
+
90
+ [The project is released under the MIT License.](./LICENSE)
@@ -0,0 +1,6 @@
1
+ # Copyright (c) 2026 WANG YAN
2
+ # Licensed under the MIT License.
3
+
4
+ from .optimizer import Adafactor8Bit
5
+
6
+ __all__ = ["Adafactor8Bit"]
@@ -0,0 +1,139 @@
1
+ // Copyright (c) 2026 WANG YAN
2
+ // Licensed under the MIT License.
3
+
4
+ #include <cuda_runtime.h>
5
+ #include <torch/extension.h>
6
+
7
+ __global__ void fused_quantize_lerp_kernel(
8
+ unsigned char* __restrict__ q,
9
+ float* __restrict__ scale,
10
+ const float* __restrict__ new_val,
11
+ const float beta,
12
+ int block_size)
13
+ {
14
+ int block_id = blockIdx.x;
15
+ int tid = threadIdx.x;
16
+ int stride = blockDim.x;
17
+ int start = block_id * block_size;
18
+
19
+ extern __shared__ float shared_mem[];
20
+ float* local_vals = shared_mem;
21
+ float* s_max = &shared_mem[block_size];
22
+
23
+ float old_scale = scale[block_id];
24
+ float thread_max = 0.0f;
25
+ float one_minus_b = 1.0f - beta;
26
+
27
+ const float4* new_val_vec = reinterpret_cast<const float4*>(new_val + start);
28
+ uchar4* q_vec = reinterpret_cast<uchar4*>(q + start);
29
+
30
+ int vec_iters = (block_size / 4) / stride;
31
+
32
+ for (int i = 0; i < vec_iters; i++) {
33
+ int idx = tid + i * stride;
34
+
35
+ float4 nv = new_val_vec[idx];
36
+ uchar4 q_val = q_vec[idx];
37
+
38
+ float upd0 = ((float)q_val.x / 255.0f * old_scale) * one_minus_b + nv.x * beta;
39
+ local_vals[idx * 4 + 0] = upd0;
40
+ thread_max = fmaxf(thread_max, upd0);
41
+
42
+ float upd1 = ((float)q_val.y / 255.0f * old_scale) * one_minus_b + nv.y * beta;
43
+ local_vals[idx * 4 + 1] = upd1;
44
+ thread_max = fmaxf(thread_max, upd1);
45
+
46
+ float upd2 = ((float)q_val.z / 255.0f * old_scale) * one_minus_b + nv.z * beta;
47
+ local_vals[idx * 4 + 2] = upd2;
48
+ thread_max = fmaxf(thread_max, upd2);
49
+
50
+ float upd3 = ((float)q_val.w / 255.0f * old_scale) * one_minus_b + nv.w * beta;
51
+ local_vals[idx * 4 + 3] = upd3;
52
+ thread_max = fmaxf(thread_max, upd3);
53
+ }
54
+
55
+
56
+ float val = thread_max;
57
+ for (int offset = 16; offset > 0; offset /= 2) {
58
+ val = fmaxf(val, __shfl_down_sync(0xffffffff, val, offset));
59
+ }
60
+
61
+
62
+ if (tid % 32 == 0) {
63
+ s_max[tid / 32] = val;
64
+ }
65
+ __syncthreads();
66
+
67
+
68
+ if (tid < 32) {
69
+
70
+ val = (tid < 8) ? s_max[tid] : 0.0f;
71
+
72
+ for (int offset = 4; offset > 0; offset /= 2) {
73
+ val = fmaxf(val, __shfl_down_sync(0xffffffff, val, offset));
74
+ }
75
+ if (tid == 0) {
76
+ s_max[0] = val;
77
+ }
78
+ }
79
+ __syncthreads();
80
+
81
+ float new_scale = fmaxf(s_max[0], 1e-12f);
82
+ float inv_scale = 255.0f / new_scale;
83
+
84
+ for (int i = 0; i < vec_iters; i++) {
85
+ int idx = tid + i * stride;
86
+
87
+ float v0 = local_vals[idx * 4 + 0];
88
+ float v1 = local_vals[idx * 4 + 1];
89
+ float v2 = local_vals[idx * 4 + 2];
90
+ float v3 = local_vals[idx * 4 + 3];
91
+
92
+ uchar4 out_q;
93
+ out_q.x = (unsigned char)fminf(fmaxf(v0 * inv_scale + 0.5f, 0.0f), 255.0f);
94
+ out_q.y = (unsigned char)fminf(fmaxf(v1 * inv_scale + 0.5f, 0.0f), 255.0f);
95
+ out_q.z = (unsigned char)fminf(fmaxf(v2 * inv_scale + 0.5f, 0.0f), 255.0f);
96
+ out_q.w = (unsigned char)fminf(fmaxf(v3 * inv_scale + 0.5f, 0.0f), 255.0f);
97
+
98
+ q_vec[idx] = out_q;
99
+ }
100
+
101
+ if (tid == 0) {
102
+ scale[block_id] = new_scale;
103
+ }
104
+ }
105
+
106
+ torch::Tensor fused_quantize_lerp_cuda(
107
+ torch::Tensor q,
108
+ torch::Tensor scale,
109
+ torch::Tensor new_val,
110
+ float beta,
111
+ int block_size)
112
+ {
113
+ TORCH_CHECK(q.scalar_type() == at::kByte, "q must be uint8");
114
+ TORCH_CHECK(scale.scalar_type() == at::kFloat, "scale must be float32");
115
+ TORCH_CHECK(new_val.scalar_type() == at::kFloat, "new_val must be float32");
116
+ TORCH_CHECK(q.is_cuda() && scale.is_cuda() && new_val.is_cuda(), "tensors must be on CUDA");
117
+ TORCH_CHECK(q.is_contiguous() && scale.is_contiguous() && new_val.is_contiguous(), "tensors must be contiguous");
118
+
119
+ int threads = 256;
120
+ TORCH_CHECK(block_size >= threads, "block_size must be >= threads");
121
+ TORCH_CHECK(block_size % 4 == 0, "block_size must be multiple of 4 for vectorization");
122
+
123
+ int num_blocks = scale.size(0);
124
+ size_t shared_mem = (block_size + 8) * sizeof(float);
125
+
126
+ fused_quantize_lerp_kernel<<<num_blocks, threads, shared_mem>>>(
127
+ q.data_ptr<unsigned char>(),
128
+ scale.data_ptr<float>(),
129
+ new_val.data_ptr<float>(),
130
+ beta,
131
+ block_size
132
+ );
133
+
134
+ return q;
135
+ }
136
+
137
+ PYBIND11_MODULE(TORCH_EXTENSION_NAME, m) {
138
+ m.def("fused_quantize_lerp", &fused_quantize_lerp_cuda, "Fused quantize lerp (CUDA)");
139
+ }
@@ -0,0 +1,383 @@
1
+ # Copyright (c) 2026 WANG YAN
2
+ # Licensed under the MIT License.
3
+
4
+ import os
5
+ import sys
6
+ import math
7
+ import logging
8
+ from typing import Tuple, Optional, Union, List, Dict, Any, Iterable
9
+
10
+ import torch
11
+ from torch import Tensor
12
+ from torch.optim import Optimizer
13
+ from torch.utils.cpp_extension import load
14
+
15
+ __all__ = ["Adafactor8Bit"]
16
+
17
+ logger = logging.getLogger(__name__)
18
+
19
+ # ==========================================
20
+ # 1. CUDA Kernel JIT Loading
21
+ # ==========================================
22
+ _CUDA_MODULE = None
23
+ _CUDA_AVAILABLE = False
24
+
25
+
26
+ def _load_cuda_module() -> bool:
27
+ global _CUDA_MODULE, _CUDA_AVAILABLE
28
+ if _CUDA_MODULE is not None or _CUDA_AVAILABLE:
29
+ return _CUDA_AVAILABLE
30
+
31
+ current_dir = os.path.dirname(os.path.abspath(__file__))
32
+ cu_path = os.path.join(current_dir, "kernels.cu")
33
+
34
+ if not os.path.exists(cu_path):
35
+ logger.warning("kernels.cu not found. Falling back to pure PyTorch implementation.")
36
+ return False
37
+
38
+ try:
39
+ is_windows = sys.platform == "win32"
40
+ extra_cflags = ["/Zc:preprocessor"] if is_windows else []
41
+ extra_cuda_cflags = ["-O3", "--use_fast_math"]
42
+ if is_windows:
43
+ extra_cuda_cflags.extend(["-Xcompiler", "/Zc:preprocessor"])
44
+
45
+ _CUDA_MODULE = load(
46
+ name="adafactor8bit_cuda",
47
+ sources=[cu_path],
48
+ extra_cflags=extra_cflags,
49
+ extra_cuda_cflags=extra_cuda_cflags,
50
+ verbose=False
51
+ )
52
+ _CUDA_AVAILABLE = True
53
+ logger.info("Adafactor8Bit: CUDA Kernel loaded successfully!")
54
+ except Exception as e:
55
+ logger.warning(f"Adafactor8Bit: Failed to load CUDA Kernel. Falling back to PyTorch. Error: {e}")
56
+
57
+ return _CUDA_AVAILABLE
58
+
59
+
60
+ # ==========================================
61
+ # 2. Quantization Utilities
62
+ # ==========================================
63
+ def _quantize_nonneg(tensor: Tensor, block_size: int = 2048) -> Tuple[Tensor, Tensor, torch.Size, int]:
64
+ """将非负 FP32 张量分块量化为 UINT8 (0-255)"""
65
+ shape = tensor.shape
66
+ flat = tensor.flatten()
67
+ pad = (block_size - flat.numel() % block_size) % block_size
68
+ if pad:
69
+ flat = torch.nn.functional.pad(flat, (0, pad))
70
+
71
+ blocks = flat.view(-1, block_size)
72
+ scale = blocks.amax(dim=1, keepdim=True).clamp(min=1e-12)
73
+ q = torch.round((blocks / scale * 255.0).clamp_(0, 255)).to(torch.uint8)
74
+ return q, scale.squeeze(-1), shape, pad
75
+
76
+
77
+ def _dequantize_nonneg(q: Tensor, scale: Tensor, shape: torch.Size, pad: int) -> Tensor:
78
+ blocks = q.float() * scale.unsqueeze(-1) / 255.0
79
+ flat = blocks.flatten()
80
+ if pad:
81
+ flat = flat[:-pad]
82
+ return flat.view(shape)
83
+
84
+
85
+ def _pad_to_block_size(tensor: Tensor, block_size: int) -> Tensor:
86
+ flat = tensor.contiguous().flatten()
87
+ pad_len = (block_size - flat.numel() % block_size) % block_size
88
+ if pad_len > 0:
89
+ return torch.nn.functional.pad(flat, (0, pad_len))
90
+ return flat
91
+
92
+
93
+ # ==========================================
94
+ # 3. Optimizer Core
95
+ # ==========================================
96
+ class Adafactor8Bit(Optimizer):
97
+ """
98
+ 8-bit Adafactor Optimizer with Fused CUDA Kernels.
99
+
100
+ Implements block-wise quantization for optimizer states, drastically reducing
101
+ memory footprint while maintaining training stability.
102
+ """
103
+
104
+ def __init__(
105
+ self,
106
+ params: Iterable[Union[Tensor, Dict[str, Any]]],
107
+ lr: float = 1e-2,
108
+ beta2_decay: float = -0.8,
109
+ eps: Tuple[Optional[float], float] = (1e-30, 1e-3),
110
+ d: float = 1.0,
111
+ weight_decay: float = 0.0,
112
+ maximize: bool = False,
113
+ relative_step: bool = False,
114
+ scale_parameter: bool = True,
115
+ quantize: bool = True,
116
+ block_size: int = 2048,
117
+ min_8bit_size: int = 4096,
118
+ ):
119
+ if not 0.0 <= lr:
120
+ raise ValueError(f"Invalid learning rate: {lr}")
121
+ if not 0.0 >= beta2_decay:
122
+ raise ValueError(f"Invalid beta2_decay: {beta2_decay}")
123
+
124
+ eps1, eps2 = eps
125
+ if eps1 is not None and not 0.0 <= eps1:
126
+ raise ValueError(f"Invalid epsilon1: {eps1}")
127
+ if not 0.0 <= eps2:
128
+ raise ValueError(f"Invalid epsilon2: {eps2}")
129
+ if not 1.0 <= d:
130
+ raise ValueError(f"Invalid clipping threshold d: {d}")
131
+ if not 0.0 <= weight_decay:
132
+ raise ValueError(f"Invalid weight_decay: {weight_decay}")
133
+
134
+ if quantize and block_size % 1024 != 0:
135
+ raise ValueError(
136
+ f"block_size must be a multiple of 1024 for CUDA float4 vectorization, "
137
+ f"but got {block_size}. (Recommended: 2048 or 4096)"
138
+ )
139
+
140
+ defaults = dict(
141
+ lr=lr, beta2_decay=beta2_decay, eps=eps, d=d, weight_decay=weight_decay,
142
+ maximize=maximize, relative_step=relative_step, scale_parameter=scale_parameter,
143
+ quantize=quantize, block_size=block_size, min_8bit_size=min_8bit_size,
144
+ )
145
+ super().__init__(params, defaults)
146
+
147
+ def _init_group(
148
+ self,
149
+ group: Dict[str, Any],
150
+ params_with_grad: List[Tensor],
151
+ grads: List[Tensor],
152
+ states: List[Dict[str, Any]],
153
+ state_steps: List[float]
154
+ ):
155
+ group_quantize = group.get("quantize", True)
156
+ block_size = group.get("block_size", 2048)
157
+ min_8bit_size = group.get("min_8bit_size", 4096)
158
+
159
+ for p in group["params"]:
160
+ if p.grad is None:
161
+ continue
162
+
163
+ force_fp32 = p.numel() < min_8bit_size
164
+ use_quant = group_quantize and not force_fp32
165
+
166
+ params_with_grad.append(p)
167
+ grads.append(p.grad)
168
+ state = self.state[p]
169
+
170
+ if len(state) == 0:
171
+ state["step"] = 0.0
172
+ state["is_quantized"] = use_quant
173
+ state["block_size"] = block_size
174
+
175
+ if p.grad.dim() > 1:
176
+ r_shape = list(p.grad.shape)
177
+ r_shape[-1] = 1
178
+ c_shape = list(p.grad.shape)
179
+ c_shape[-2] = 1
180
+ if use_quant:
181
+ r_tmp = torch.zeros(r_shape, device=p.device)
182
+ q, s, sh, pad = _quantize_nonneg(r_tmp, block_size)
183
+ state["row_var_q"], state["row_var_scale"], state["row_var_shape"], state["row_var_pad"] = q, s, sh, pad
184
+
185
+ c_tmp = torch.zeros(c_shape, device=p.device)
186
+ q, s, sh, pad = _quantize_nonneg(c_tmp, block_size)
187
+ state["col_var_q"], state["col_var_scale"], state["col_var_shape"], state["col_var_pad"] = q, s, sh, pad
188
+ else:
189
+ state["row_var"] = torch.zeros(r_shape, device=p.device)
190
+ state["col_var"] = torch.zeros(c_shape, device=p.device)
191
+ else:
192
+ if use_quant:
193
+ v_tmp = torch.zeros_like(p.grad, memory_format=torch.preserve_format)
194
+ q, s, sh, pad = _quantize_nonneg(v_tmp, block_size)
195
+ state["variance_q"], state["variance_scale"], state["variance_shape"], state["variance_pad"] = q, s, sh, pad
196
+ else:
197
+ state["variance"] = torch.zeros_like(p.grad, memory_format=torch.preserve_format)
198
+ else:
199
+ # Checkpoint Compatibility & Device Alignment
200
+ if torch.is_tensor(state["step"]):
201
+ state["step"] = float(state["step"].item())
202
+ elif not isinstance(state["step"], (int, float)):
203
+ state["step"] = float(state["step"])
204
+
205
+ for k in list(state.keys()):
206
+ if isinstance(state[k], torch.Tensor):
207
+ if state[k].device != p.device:
208
+ state[k] = state[k].to(p.device)
209
+
210
+ # Defensive dtype casting for legacy checkpoints
211
+ if k.endswith("_q") and state[k].dtype != torch.uint8:
212
+ state[k] = state[k].to(torch.uint8)
213
+ scale_key = k.replace("_q", "_scale")
214
+ if scale_key in state and state[scale_key].dtype != torch.float32:
215
+ state[scale_key] = state[scale_key].to(torch.float32)
216
+
217
+ curr_block_size = state.get("block_size", block_size)
218
+
219
+ # Auto Upgrade: FP32 -> 8-bit
220
+ if use_quant and not state.get("is_quantized", False):
221
+ if p.grad.dim() > 1:
222
+ if "row_var" in state and "row_var_q" not in state:
223
+ q, s, sh, pad = _quantize_nonneg(state["row_var"], curr_block_size)
224
+ state["row_var_q"], state["row_var_scale"], state["row_var_shape"], state["row_var_pad"] = q, s, sh, pad
225
+ del state["row_var"]
226
+ if "col_var" in state and "col_var_q" not in state:
227
+ q, s, sh, pad = _quantize_nonneg(state["col_var"], curr_block_size)
228
+ state["col_var_q"], state["col_var_scale"], state["col_var_shape"], state["col_var_pad"] = q, s, sh, pad
229
+ del state["col_var"]
230
+ else:
231
+ if "variance" in state and "variance_q" not in state:
232
+ q, s, sh, pad = _quantize_nonneg(state["variance"], curr_block_size)
233
+ state["variance_q"], state["variance_scale"], state["variance_shape"], state["variance_pad"] = q, s, sh, pad
234
+ del state["variance"]
235
+ state["is_quantized"] = True
236
+
237
+ # Auto Downgrade: 8-bit -> FP32
238
+ elif not use_quant and state.get("is_quantized", False):
239
+ if p.grad.dim() > 1:
240
+ if "row_var_q" in state:
241
+ state["row_var"] = _dequantize_nonneg(state.pop("row_var_q"), state.pop("row_var_scale"), state.pop("row_var_shape"), state.pop("row_var_pad"))
242
+ if "col_var_q" in state:
243
+ state["col_var"] = _dequantize_nonneg(state.pop("col_var_q"), state.pop("col_var_scale"), state.pop("col_var_shape"), state.pop("col_var_pad"))
244
+ else:
245
+ if "variance_q" in state:
246
+ state["variance"] = _dequantize_nonneg(state.pop("variance_q"), state.pop("variance_scale"), state.pop("variance_shape"), state.pop("variance_pad"))
247
+ state["is_quantized"] = False
248
+
249
+ if "is_quantized" not in state:
250
+ state["is_quantized"] = ("row_var_q" in state or "col_var_q" in state or "variance_q" in state)
251
+ if "block_size" not in state:
252
+ state["block_size"] = block_size
253
+
254
+ states.append(state)
255
+ state_steps.append(state["step"])
256
+
257
+ @torch.no_grad()
258
+ def step(self, closure=None):
259
+ """Performs a single optimization step."""
260
+ loss = None
261
+ if closure is not None:
262
+ with torch.enable_grad():
263
+ loss = closure()
264
+
265
+ for group in self.param_groups:
266
+ params_with_grad, grads, states, state_steps = [], [], [], []
267
+ eps1, eps2 = group["eps"]
268
+ self._init_group(group, params_with_grad, grads, states, state_steps)
269
+
270
+ for i in range(len(params_with_grad)):
271
+ _update_param_8bit(
272
+ params_with_grad[i], grads[i], states[i],
273
+ d=group["d"], lr=group["lr"], beta2_decay=group["beta2_decay"],
274
+ weight_decay=group["weight_decay"], eps1=eps1, eps2=eps2,
275
+ maximize=group["maximize"], relative_step=group["relative_step"],
276
+ scale_parameter=group["scale_parameter"], block_size=group.get("block_size", 2048),
277
+ )
278
+ return loss
279
+
280
+
281
+ # ==========================================
282
+ # 4. Parameter Update Logic
283
+ # ==========================================
284
+ def _update_param_8bit(
285
+ param: Tensor, grad: Tensor,
286
+ state: Dict[str, Any],
287
+ d: float, lr: Union[float, Tensor],
288
+ beta2_decay: float, weight_decay: float,
289
+ eps1: Optional[float],
290
+ eps2: float,
291
+ maximize: bool,
292
+ relative_step: bool,
293
+ scale_parameter: bool,
294
+ block_size: int
295
+ ):
296
+ if maximize:
297
+ grad = -grad
298
+ if eps1 is None:
299
+ eps1 = torch.finfo(param.dtype).eps
300
+
301
+ quantize = state.get("is_quantized", False)
302
+ curr_block_size = state.get("block_size", block_size)
303
+
304
+ # 1. Pure CPU step increment (Zero Sync)
305
+ step = state["step"] + 1.0
306
+ state["step"] = step
307
+ beta_val = math.pow(step, beta2_decay)
308
+
309
+ # 2. Learning Rate scheduling
310
+ if isinstance(lr, float):
311
+ rho = min(lr, 1.0 / math.sqrt(step)) if relative_step else lr
312
+ rho_t = torch.tensor(rho, device=param.device, dtype=torch.float32)
313
+ else:
314
+ if relative_step:
315
+ step_t = torch.tensor(step, device=param.device, dtype=torch.float32)
316
+ rho_t = torch.minimum(step_t.rsqrt(), lr)
317
+ else:
318
+ rho_t = lr
319
+
320
+ if scale_parameter:
321
+ param_rms = param.norm(2) / math.sqrt(param.numel())
322
+ alpha = torch.clamp(param_rms, min=eps2) * rho_t
323
+ else:
324
+ alpha = rho_t
325
+
326
+ if weight_decay != 0:
327
+ param.mul_(1 - alpha * weight_decay)
328
+
329
+ # 3. Second Moment Estimation
330
+ if grad.dim() > 1:
331
+ row_mean = torch.norm(grad, dim=-1, keepdim=True).square_().div_(grad.size(-1)).add_(eps1)
332
+ col_mean = torch.norm(grad, dim=-2, keepdim=True).square_().div_(grad.size(-2)).add_(eps1)
333
+
334
+ if quantize:
335
+ if _load_cuda_module():
336
+ row_mean_padded = _pad_to_block_size(row_mean, curr_block_size)
337
+ col_mean_padded = _pad_to_block_size(col_mean, curr_block_size)
338
+
339
+ _CUDA_MODULE.fused_quantize_lerp(state["row_var_q"], state["row_var_scale"], row_mean_padded, beta_val, curr_block_size)
340
+ _CUDA_MODULE.fused_quantize_lerp(state["col_var_q"], state["col_var_scale"], col_mean_padded, beta_val, curr_block_size)
341
+
342
+ row_var = _dequantize_nonneg(state["row_var_q"], state["row_var_scale"], state["row_var_shape"], state["row_var_pad"])
343
+ col_var = _dequantize_nonneg(state["col_var_q"], state["col_var_scale"], state["col_var_shape"], state["col_var_pad"])
344
+ else:
345
+ row_var = _dequantize_nonneg(state["row_var_q"], state["row_var_scale"], state["row_var_shape"], state["row_var_pad"])
346
+ col_var = _dequantize_nonneg(state["col_var_q"], state["col_var_scale"], state["col_var_shape"], state["col_var_pad"])
347
+ row_var.lerp_(row_mean, beta_val)
348
+ col_var.lerp_(col_mean, beta_val)
349
+ q, s, sh, pad = _quantize_nonneg(row_var, curr_block_size)
350
+ state["row_var_q"], state["row_var_scale"], state["row_var_shape"], state["row_var_pad"] = q, s, sh, pad
351
+ q, s, sh, pad = _quantize_nonneg(col_var, curr_block_size)
352
+ state["col_var_q"], state["col_var_scale"], state["col_var_shape"], state["col_var_pad"] = q, s, sh, pad
353
+ else:
354
+ row_var = state["row_var"]
355
+ col_var = state["col_var"]
356
+ row_var.lerp_(row_mean, beta_val)
357
+ col_var.lerp_(col_mean, beta_val)
358
+
359
+ var_estimate = row_var @ col_var
360
+ var_estimate.div_(row_var.mean(dim=-2, keepdim=True).clamp_(min=torch.finfo(param.dtype).eps))
361
+
362
+ else:
363
+ grad_sq = grad.square().add_(eps1)
364
+ if quantize:
365
+ if _load_cuda_module():
366
+ grad_sq_padded = _pad_to_block_size(grad_sq, curr_block_size)
367
+ _CUDA_MODULE.fused_quantize_lerp(state["variance_q"], state["variance_scale"], grad_sq_padded, beta_val, curr_block_size)
368
+ variance = _dequantize_nonneg(state["variance_q"], state["variance_scale"], state["variance_shape"], state["variance_pad"])
369
+ else:
370
+ variance = _dequantize_nonneg(state["variance_q"], state["variance_scale"], state["variance_shape"], state["variance_pad"])
371
+ variance.lerp_(grad_sq, beta_val)
372
+ q, s, sh, pad = _quantize_nonneg(variance, curr_block_size)
373
+ state["variance_q"], state["variance_scale"], state["variance_shape"], state["variance_pad"] = q, s, sh, pad
374
+ else:
375
+ variance = state["variance"]
376
+ variance.lerp_(grad_sq, beta_val)
377
+
378
+ var_estimate = variance
379
+
380
+ # 4. Parameter Update & Gradient Clipping
381
+ update = var_estimate.clamp_(min=torch.finfo(param.dtype).eps).rsqrt_().mul_(grad)
382
+ denom = torch.clamp(update.norm(2) / (math.sqrt(update.numel()) * d), min=1.0)
383
+ param.add_(update, alpha=-alpha / denom)
@@ -0,0 +1,117 @@
1
+ Metadata-Version: 2.4
2
+ Name: adafactor8bit
3
+ Version: 0.1.0
4
+ Summary: 8-bit Adafactor Optimizer with Fused CUDA Kernels
5
+ Home-page: https://github.com/yanfeiwong/adafactor-8bit
6
+ Author: WANG YAN
7
+ Author-email: yanfeiwong1997@outlook.com
8
+ Classifier: Programming Language :: Python :: 3
9
+ Classifier: License :: OSI Approved :: MIT License
10
+ Classifier: Operating System :: OS Independent
11
+ Classifier: Topic :: Scientific/Engineering :: Artificial Intelligence
12
+ Requires-Python: >=3.10
13
+ Description-Content-Type: text/markdown
14
+ License-File: LICENSE
15
+ Requires-Dist: torch>=2.1
16
+ Requires-Dist: ninja
17
+ Dynamic: author
18
+ Dynamic: author-email
19
+ Dynamic: classifier
20
+ Dynamic: description
21
+ Dynamic: description-content-type
22
+ Dynamic: home-page
23
+ Dynamic: license-file
24
+ Dynamic: requires-dist
25
+ Dynamic: requires-python
26
+ Dynamic: summary
27
+
28
+ **English** | [中文](./README_ZH.md)
29
+
30
+ # Adafactor 8-bit with Fused CUDA Kernels
31
+
32
+ An 8-bit Adafactor optimizer designed for memory-efficient large-scale model training.
33
+
34
+ It uses fused CUDA kernels and block-wise quantization to reduce optimizer state memory while maintaining training stability, making it suitable for training large models such as LLMs and diffusion models.
35
+
36
+ ## Key Features
37
+
38
+ - **Fused CUDA Kernel**: Integrates dequantization, EMA updates, Warp-Shuffle reduction, and requantization into a single kernel, utilizing `float4` vectorization to maximize memory bandwidth utilization.
39
+ - **Zero CPU-GPU Sync**: Refactored the control flow to eliminate implicit synchronizations, ensuring the GPU computation pipeline runs asynchronously at high speed.
40
+ - **Cross-Platform JIT**: Utilizes JIT (Just-In-Time) automatic compilation for seamless setup across Windows and Linux environments.
41
+
42
+ ## Algorithm Details
43
+
44
+ Rebuilt upon the official PyTorch Adafactor, the mathematical logic **aligns more closely with the original paper and `HuggingFace transformers`**. Key differences include:
45
+
46
+ 1. **Safe Injection of `eps1`**: The official PyTorch implementation defaults to `eps1=None` and relies on `clamp`, which can lead to NaNs when encountering zero or extremely small gradients. This project adopts the original `grad_squared + eps1` approach, fundamentally guaranteeing the strict positive definiteness of the second moment and preventing training crashes caused by `rsqrt(0)`.
47
+ 2. **Coupled Weight Decay**: Unlike the official PyTorch implementation which decouples Weight Decay from RMS, this project retains the Coupled mechanism from the original paper (Weight Decay multiplied by the effective learning rate that includes RMS scaling).
48
+ 3. **Standard Parameter Support**: Fully retains core Adafactor switches such as `relative_step` and `scale_parameter`, ensuring compatibility with existing learning rate scheduling strategies.
49
+
50
+ ## Performance
51
+
52
+ - **Memory Footprint**: The memory usage of optimizer states is **significantly lower than `AdamW8Bit`** (bitsandbytes), making it an ideal choice for training massive models or when memory-constrained.
53
+ - **Training Speed**: The Fused Kernel and Zero-Sync design enable it to achieve step speeds comparable to mainstream 8-bit optimizers.
54
+ - **Quantization Precision & Stability**: The second moment (variance) in Adafactor is always non-negative, so we map it to `UINT8 (0~255)`. Compared to traditional 8-bit optimizers that map to `INT8 (-127~127)`, providing higher effective quantization precision within the non-negative variance domain.
55
+
56
+ ## Installation
57
+
58
+ This project uses JIT (Just-In-Time) compilation.
59
+
60
+ Please ensure torch and ninja are installed, and a CUDA compiler (such as MSVC or GCC) is available in your environment.
61
+
62
+ If CUDA compilation fails, the optimizer will automatically fall back to the pure PyTorch implementation.
63
+
64
+
65
+ ```bash
66
+ pip install git+https://github.com/yanfeiwong/adafactor-8bit.git
67
+ ```
68
+
69
+ ## Usage Example
70
+
71
+ It is recommended to use `param_groups` to keep sensitive layers (Embedding, Norm, Bias) in FP32, enabling 8-bit quantization only for large 2D weight matrices.
72
+
73
+ ```python
74
+ import torch
75
+ import torch.nn as nn
76
+ from adafactor8bit import Adafactor8Bit
77
+
78
+ def get_param_groups(model, weight_decay=1e-2):
79
+ decay, no_decay = [], []
80
+ for name, param in model.named_parameters():
81
+ if not param.requires_grad: continue
82
+ # Protect 1D tensors, biases, norms, and embeddings
83
+ if param.ndim <= 1 or "bias" in name or "norm" in name or "embed" in name:
84
+ no_decay.append(param)
85
+ else:
86
+ decay.append(param)
87
+
88
+ return [
89
+ {"params": decay, "weight_decay": weight_decay, "quantize": True},
90
+ {"params": no_decay, "weight_decay": 0.0, "quantize": False}
91
+ ]
92
+
93
+ model = MyModel().cuda()
94
+ optimizer = Adafactor8Bit(
95
+ get_param_groups(model),
96
+ lr=1e-3,
97
+ relative_step=False,
98
+ block_size=2048,
99
+ min_8bit_size=4096
100
+ )
101
+
102
+ # Training loop...
103
+ ```
104
+
105
+ For a complete example, please refer to [basic_usage.py](./examples/basic_usage.py).
106
+
107
+ ## Acknowledgements
108
+
109
+ Thanks to the large language models Qwen and DeepSeek for valuable technical discussions and code reviews on CUDA low-level optimization, memory safety mechanisms, and cross-platform compilation pipeline design.
110
+
111
+ Thanks to Tim Dettmers for the inspiration from the paper [8-BIT OPTIMIZERS VIA BLOCK-WISE QUANTIZATION](https://arxiv.org/pdf/2110.02861) and the [bitsandbytes](https://github.com/bitsandbytes-foundation/bitsandbytes) library.
112
+
113
+ Thanks to the PyTorch team for providing the foundational Optimizer implementation and the C++ Extension toolchain.
114
+
115
+ ## License
116
+
117
+ [The project is released under the MIT License.](./LICENSE)
@@ -0,0 +1,12 @@
1
+ LICENSE
2
+ MANIFEST.in
3
+ README.md
4
+ setup.py
5
+ adafactor8bit/__init__.py
6
+ adafactor8bit/kernels.cu
7
+ adafactor8bit/optimizer.py
8
+ adafactor8bit.egg-info/PKG-INFO
9
+ adafactor8bit.egg-info/SOURCES.txt
10
+ adafactor8bit.egg-info/dependency_links.txt
11
+ adafactor8bit.egg-info/requires.txt
12
+ adafactor8bit.egg-info/top_level.txt
@@ -0,0 +1,2 @@
1
+ torch>=2.1
2
+ ninja
@@ -0,0 +1 @@
1
+ adafactor8bit
@@ -0,0 +1,4 @@
1
+ [egg_info]
2
+ tag_build =
3
+ tag_date = 0
4
+
@@ -0,0 +1,33 @@
1
+ # Copyright (c) 2026 WANG YAN
2
+ # Licensed under the MIT License.
3
+
4
+ from pathlib import Path
5
+ from setuptools import setup, find_packages
6
+
7
+ this_directory = Path(__file__).parent
8
+ long_description = (this_directory / "README.md").read_text(encoding="utf-8")
9
+
10
+ setup(
11
+ name="adafactor8bit",
12
+ version="0.1.0",
13
+ description="8-bit Adafactor Optimizer with Fused CUDA Kernels",
14
+ author="WANG YAN",
15
+ author_email="yanfeiwong1997@outlook.com",
16
+ url="https://github.com/yanfeiwong/adafactor-8bit",
17
+ packages=find_packages(),
18
+ include_package_data=True,
19
+ package_data={"adafactor8bit": ["*.cu"]},
20
+ install_requires=[
21
+ "torch>=2.1",
22
+ "ninja",
23
+ ],
24
+ python_requires=">=3.10",
25
+ long_description=long_description,
26
+ long_description_content_type="text/markdown",
27
+ classifiers=[
28
+ "Programming Language :: Python :: 3",
29
+ "License :: OSI Approved :: MIT License",
30
+ "Operating System :: OS Independent",
31
+ "Topic :: Scientific/Engineering :: Artificial Intelligence",
32
+ ],
33
+ )