Skip to content

Commit 706ec24

Browse files
Ruff fixes (#984)
* Adjust Ruff configuration * do not autofix always * be less strict around tests and benchmarks * adjust ignores for now * Ruff: autofix I and F401 * Apply ruff autofixes * Fix RUF013 complaint * Fix mutable default in replace_linear * Don't use bare except * Wrap bitsandbytes.__main__ entrypoint in function; fix "sensible" typo * Fix ruff B008 (function call in arguments) * Add ruff noqas as suitable * Fix RUF005 (splat instead of concatenating) * Fix B018 (useless expression) * Add pre-commit configuration + GitHub Actions lint workflow * Fix unused `e` in bitsandbytes/__main__.py * fix merge conflict resolution error * run pre-commit hook --------- Co-authored-by: Titus <[email protected]>
1 parent a8c9dfa commit 706ec24

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

44 files changed

+267
-202
lines changed

.github/workflows/lint.yml

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,19 @@
1+
name: Lint
2+
3+
on:
4+
push:
5+
branches:
6+
- main
7+
pull_request:
8+
9+
jobs:
10+
Lint:
11+
runs-on: ubuntu-latest
12+
steps:
13+
- uses: actions/checkout@v4
14+
- uses: actions/setup-python@v4
15+
with:
16+
python-version: "3.12"
17+
- uses: pre-commit/[email protected]
18+
env:
19+
RUFF_OUTPUT_FORMAT: github

.pre-commit-config.yaml

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,8 @@
1+
repos:
2+
- repo: https://github.com/astral-sh/ruff-pre-commit
3+
rev: v0.1.15
4+
hooks:
5+
- id: ruff
6+
args:
7+
- --fix
8+
# - id: ruff-format # TODO: enable when the time is right

benchmarking/switchback/make_plot_with_jsonl.py

Lines changed: 2 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,7 @@
1-
import matplotlib.pyplot as plt
2-
import pandas as pd
3-
import numpy as np
4-
import os
51

62
import matplotlib.gridspec as gridspec
3+
import matplotlib.pyplot as plt
4+
import pandas as pd
75

86
cmap=plt.get_cmap('cool')
97

benchmarking/switchback/speed_benchmark.py

Lines changed: 14 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -1,14 +1,22 @@
11
import json
2-
32
import time
3+
44
import torch
5-
import torch.nn as nn
65

6+
from bitsandbytes.triton.int8_matmul_mixed_dequantize import (
7+
int8_matmul_mixed_dequantize,
8+
)
9+
from bitsandbytes.triton.int8_matmul_rowwise_dequantize import (
10+
int8_matmul_rowwise_dequantize,
11+
)
12+
from bitsandbytes.triton.quantize_columnwise_and_transpose import (
13+
quantize_columnwise_and_transpose,
14+
)
15+
from bitsandbytes.triton.quantize_global import (
16+
quantize_global,
17+
quantize_global_transpose,
18+
)
719
from bitsandbytes.triton.quantize_rowwise import quantize_rowwise
8-
from bitsandbytes.triton.quantize_columnwise_and_transpose import quantize_columnwise_and_transpose
9-
from bitsandbytes.triton.int8_matmul_rowwise_dequantize import int8_matmul_rowwise_dequantize
10-
from bitsandbytes.triton.quantize_global import quantize_global, quantize_global_transpose
11-
from bitsandbytes.triton.int8_matmul_mixed_dequantize import int8_matmul_mixed_dequantize
1220

1321
# KNOW ISSUE: need to optimize "w_quantize_colwise_transpose" when embeddim is too large.
1422

bitsandbytes/__init__.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -3,14 +3,14 @@
33
# This source code is licensed under the MIT license found in the
44
# LICENSE file in the root directory of this source tree.
55

6-
from . import cuda_setup, utils, research
6+
from . import cuda_setup, research, utils
77
from .autograd._functions import (
88
MatmulLtState,
99
bmm_cublas,
1010
matmul,
11+
matmul_4bit,
1112
matmul_cublas,
1213
mm_cublas,
13-
matmul_4bit
1414
)
1515
from .cextension import COMPILED_WITH_CUDA
1616
from .nn import modules

bitsandbytes/__main__.py

Lines changed: 45 additions & 58 deletions
Original file line numberDiff line numberDiff line change
@@ -1,11 +1,7 @@
11
import os
2+
from os.path import isdir
23
import sys
3-
import shlex
4-
import subprocess
5-
64
from warnings import warn
7-
from typing import Tuple
8-
from os.path import isdir
95

106
import torch
117

@@ -20,7 +16,7 @@ def find_file_recursive(folder, filename):
2016
out = glob.glob(os.path.join(folder, "**", filename + ext))
2117
outs.extend(out)
2218
except Exception as e:
23-
raise RuntimeError('Error: Something when wrong when trying to find file. {e}')
19+
raise RuntimeError('Error: Something when wrong when trying to find file.') from e
2420

2521
return outs
2622

@@ -62,14 +58,11 @@ def generate_bug_report_information():
6258
print_header(f"{path} CUDA PATHS")
6359
paths = find_file_recursive(path, '*cuda*')
6460
print(paths)
65-
except:
66-
print(f'Could not read LD_LIBRARY_PATH: {path}')
61+
except Exception as e:
62+
print(f'Could not read LD_LIBRARY_PATH: {path} ({e})')
6763
print('')
6864

6965

70-
71-
72-
7366
def print_header(
7467
txt: str, width: int = HEADER_WIDTH, filler: str = "+"
7568
) -> None:
@@ -78,67 +71,61 @@ def print_header(
7871

7972

8073
def print_debug_info() -> None:
74+
from . import PACKAGE_GITHUB_URL
8175
print(
8276
"\nAbove we output some debug information. Please provide this info when "
8377
f"creating an issue via {PACKAGE_GITHUB_URL}/issues/new/choose ...\n"
8478
)
8579

8680

87-
generate_bug_report_information()
81+
def main():
82+
generate_bug_report_information()
8883

84+
from . import COMPILED_WITH_CUDA
85+
from .cuda_setup.main import get_compute_capabilities
8986

90-
from . import COMPILED_WITH_CUDA, PACKAGE_GITHUB_URL
91-
from .cuda_setup.env_vars import to_be_ignored
92-
from .cuda_setup.main import get_compute_capabilities
93-
87+
print_header("OTHER")
88+
print(f"COMPILED_WITH_CUDA = {COMPILED_WITH_CUDA}")
89+
print(f"COMPUTE_CAPABILITIES_PER_GPU = {get_compute_capabilities()}")
90+
print_header("")
91+
print_header("DEBUG INFO END")
92+
print_header("")
93+
print("Checking that the library is importable and CUDA is callable...")
94+
print("\nWARNING: Please be sure to sanitize sensitive info from any such env vars!\n")
9495

95-
print_header("OTHER")
96-
print(f"COMPILED_WITH_CUDA = {COMPILED_WITH_CUDA}")
97-
print(f"COMPUTE_CAPABILITIES_PER_GPU = {get_compute_capabilities()}")
98-
print_header("")
99-
print_header("DEBUG INFO END")
100-
print_header("")
101-
print(
102-
"""
103-
Running a quick check that:
104-
+ library is importable
105-
+ CUDA function is callable
106-
"""
107-
)
108-
print("\nWARNING: Please be sure to sanitize sensible info from any such env vars!\n")
96+
try:
97+
from bitsandbytes.optim import Adam
10998

110-
try:
111-
from bitsandbytes.optim import Adam
99+
p = torch.nn.Parameter(torch.rand(10, 10).cuda())
100+
a = torch.rand(10, 10).cuda()
112101

113-
p = torch.nn.Parameter(torch.rand(10, 10).cuda())
114-
a = torch.rand(10, 10).cuda()
102+
p1 = p.data.sum().item()
115103

116-
p1 = p.data.sum().item()
104+
adam = Adam([p])
117105

118-
adam = Adam([p])
106+
out = a * p
107+
loss = out.sum()
108+
loss.backward()
109+
adam.step()
119110

120-
out = a * p
121-
loss = out.sum()
122-
loss.backward()
123-
adam.step()
111+
p2 = p.data.sum().item()
124112

125-
p2 = p.data.sum().item()
113+
assert p1 != p2
114+
print("SUCCESS!")
115+
print("Installation was successful!")
116+
except ImportError:
117+
print()
118+
warn(
119+
f"WARNING: {__package__} is currently running as CPU-only!\n"
120+
"Therefore, 8-bit optimizers and GPU quantization are unavailable.\n\n"
121+
f"If you think that this is so erroneously,\nplease report an issue!"
122+
)
123+
print_debug_info()
124+
except Exception as e:
125+
print(e)
126+
print_debug_info()
127+
sys.exit(1)
126128

127-
assert p1 != p2
128-
print("SUCCESS!")
129-
print("Installation was successful!")
130-
sys.exit(0)
131129

132-
except ImportError:
133-
print()
134-
warn(
135-
f"WARNING: {__package__} is currently running as CPU-only!\n"
136-
"Therefore, 8-bit optimizers and GPU quantization are unavailable.\n\n"
137-
f"If you think that this is so erroneously,\nplease report an issue!"
138-
)
139-
print_debug_info()
140-
sys.exit(0)
141-
except Exception as e:
142-
print(e)
143-
print_debug_info()
144-
sys.exit(1)
130+
if __name__ == "__main__":
131+
main()

bitsandbytes/autograd/__init__.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1 +1 @@
1-
from ._functions import undo_layout, get_inverse_transform_indices
1+
from ._functions import get_inverse_transform_indices, undo_layout

bitsandbytes/autograd/_functions.py

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,8 @@
1-
import operator
2-
import warnings
31
from dataclasses import dataclass
42
from functools import reduce # Required in Python 3
5-
from typing import Tuple, Optional, Callable
3+
import operator
4+
from typing import Callable, Optional, Tuple
5+
import warnings
66
from warnings import warn
77

88
import torch

bitsandbytes/cextension.py

Lines changed: 3 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -1,12 +1,9 @@
11
import ctypes as ct
2-
import os
3-
import torch
4-
5-
from pathlib import Path
62
from warnings import warn
73

8-
from bitsandbytes.cuda_setup.main import CUDASetup
4+
import torch
95

6+
from bitsandbytes.cuda_setup.main import CUDASetup
107

118
setup = CUDASetup.get_instance()
129
if setup.initialized != True:
@@ -25,7 +22,7 @@
2522
Inspect the output of the command and see if you can locate CUDA libraries. You might need to add them
2623
to your LD_LIBRARY_PATH. If you suspect a bug, please take the information from python -m bitsandbytes
2724
and open an issue at: https://github.com/TimDettmers/bitsandbytes/issues''')
28-
lib.cadam32bit_grad_fp32 # runs on an error if the library could not be found -> COMPILED_WITH_CUDA=False
25+
_ = lib.cadam32bit_grad_fp32 # runs on an error if the library could not be found -> COMPILED_WITH_CUDA=False
2926
lib.get_context.restype = ct.c_void_p
3027
lib.get_cusparse.restype = ct.c_void_p
3128
lib.cget_managed_ptr.restype = ct.c_void_p

bitsandbytes/cuda_setup/main.py

Lines changed: 24 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -17,15 +17,15 @@
1717
"""
1818

1919
import ctypes as ct
20-
import os
2120
import errno
21+
import os
22+
from pathlib import Path
2223
import platform
23-
import torch
24+
from typing import Set, Union
2425
from warnings import warn
25-
from itertools import product
2626

27-
from pathlib import Path
28-
from typing import Set, Union
27+
import torch
28+
2929
from .env_vars import get_potentially_lib_path_containing_env_vars
3030

3131
# these are the most common libs names
@@ -111,14 +111,16 @@ def manual_override(self):
111111
if torch.cuda.is_available():
112112
if 'BNB_CUDA_VERSION' in os.environ:
113113
if len(os.environ['BNB_CUDA_VERSION']) > 0:
114-
warn((f'\n\n{"="*80}\n'
115-
'WARNING: Manual override via BNB_CUDA_VERSION env variable detected!\n'
116-
'BNB_CUDA_VERSION=XXX can be used to load a bitsandbytes version that is different from the PyTorch CUDA version.\n'
117-
'If this was unintended set the BNB_CUDA_VERSION variable to an empty string: export BNB_CUDA_VERSION=\n'
118-
'If you use the manual override make sure the right libcudart.so is in your LD_LIBRARY_PATH\n'
119-
'For example by adding the following to your .bashrc: export LD_LIBRARY_PATH=$LD_LIBRARY_PATH:<path_to_cuda_dir/lib64\n'
120-
f'Loading CUDA version: BNB_CUDA_VERSION={os.environ["BNB_CUDA_VERSION"]}'
121-
f'\n{"="*80}\n\n'))
114+
warn(
115+
f'\n\n{"=" * 80}\n'
116+
'WARNING: Manual override via BNB_CUDA_VERSION env variable detected!\n'
117+
'BNB_CUDA_VERSION=XXX can be used to load a bitsandbytes version that is different from the PyTorch CUDA version.\n'
118+
'If this was unintended set the BNB_CUDA_VERSION variable to an empty string: export BNB_CUDA_VERSION=\n'
119+
'If you use the manual override make sure the right libcudart.so is in your LD_LIBRARY_PATH\n'
120+
'For example by adding the following to your .bashrc: export LD_LIBRARY_PATH=$LD_LIBRARY_PATH:<path_to_cuda_dir/lib64\n'
121+
f'Loading CUDA version: BNB_CUDA_VERSION={os.environ["BNB_CUDA_VERSION"]}'
122+
f'\n{"=" * 80}\n\n'
123+
)
122124
binary_name = self.binary_name.rsplit(".", 1)[0]
123125
suffix = ".so" if os.name != "nt" else ".dll"
124126
self.binary_name = binary_name[:-3] + f'{os.environ["BNB_CUDA_VERSION"]}.{suffix}'
@@ -207,7 +209,7 @@ def remove_non_existent_dirs(candidate_paths: Set[Path]) -> Set[Path]:
207209
try:
208210
if path.exists():
209211
existent_directories.add(path)
210-
except PermissionError as pex:
212+
except PermissionError:
211213
# Handle the PermissionError first as it is a subtype of OSError
212214
# https://docs.python.org/3/library/exceptions.html#exception-hierarchy
213215
pass
@@ -217,8 +219,10 @@ def remove_non_existent_dirs(candidate_paths: Set[Path]) -> Set[Path]:
217219

218220
non_existent_directories: Set[Path] = candidate_paths - existent_directories
219221
if non_existent_directories:
220-
CUDASetup.get_instance().add_log_entry("The following directories listed in your path were found to "
221-
f"be non-existent: {non_existent_directories}", is_warning=False)
222+
CUDASetup.get_instance().add_log_entry(
223+
f"The following directories listed in your path were found to be non-existent: {non_existent_directories}",
224+
is_warning=False,
225+
)
222226

223227
return existent_directories
224228

@@ -360,8 +364,10 @@ def evaluate_cuda_setup():
360364
cuda_version_string = get_cuda_version()
361365

362366
cuda_setup.add_log_entry(f"CUDA SETUP: PyTorch settings found: CUDA_VERSION={cuda_version_string}, Highest Compute Capability: {cc}.")
363-
cuda_setup.add_log_entry(f"CUDA SETUP: To manually override the PyTorch CUDA version please see:"
364-
"https://github.com/TimDettmers/bitsandbytes/blob/main/how_to_use_nonpytorch_cuda.md")
367+
cuda_setup.add_log_entry(
368+
"CUDA SETUP: To manually override the PyTorch CUDA version please see:"
369+
"https://github.com/TimDettmers/bitsandbytes/blob/main/how_to_use_nonpytorch_cuda.md"
370+
)
365371

366372

367373
# 7.5 is the minimum CC vor cublaslt

0 commit comments

Comments
 (0)