benchmake 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.

Potentially problematic release.


This version of benchmake might be problematic. Click here for more details.

@@ -0,0 +1,423 @@
1
+ #BenchMake
2
+ #(c) 2025, Prof Dr Amanda S Barnard PhD DSc
3
+ # Version 1.0, 06/02/2025
4
+
5
+ import os
6
+ import math
7
+ import numpy as np
8
+ import pandas as pd
9
+ from joblib import Parallel, delayed
10
+ from sklearn.feature_extraction.text import CountVectorizer
11
+ import hashlib
12
+
13
+ # Attempt to import CuPy for GPU computations and check GPU compatibility
14
+ try:
15
+ import cupy as cp
16
+ # Check if at least one CUDA-capable device is available
17
+ if cp.cuda.runtime.getDeviceCount() > 0:
18
+ try:
19
+ from cupy.cuda import Device
20
+ device = Device(0) # Use the first device
21
+ _ = device.compute_capability # Verify compatibility
22
+ gpu_available = True
23
+ cp.random.seed(42)
24
+ print("GPU is available. Using CuPy for GPU computations.")
25
+ except cp.cuda.runtime.CUDARuntimeError as e:
26
+ cp = None
27
+ gpu_available = False
28
+ print(f"Warning: CuPy is installed but the GPU is not compatible: {e}. Reverting to CPU.")
29
+ else:
30
+ cp = None
31
+ gpu_available = False
32
+ print("Warning: No CUDA-capable devices found. Reverting to CPU.")
33
+ except ImportError:
34
+ cp = None
35
+ gpu_available = False
36
+ print("CuPy not installed. Using NumPy for CPU computations.")
37
+ except Exception as e:
38
+ cp = None
39
+ gpu_available = False
40
+ print(f"Warning: An unexpected error occurred while initializing CuPy: {e}\nReverting to CPU computations.")
41
+
42
+ # Fixed random seed for NumPy
43
+ np.random.seed(42)
44
+
45
+ class NMF:
46
+ FIXED_RANDOM_STATE = 42 # Fixed seed for determinism
47
+
48
+ def __init__(self, n_components, max_iter=1000, tol=1e-4, random_state=FIXED_RANDOM_STATE):
49
+ self.n_components = n_components
50
+ self.max_iter = max_iter
51
+ self.tol = tol
52
+ self.random_state = random_state
53
+
54
+ def fit_transform(self, X):
55
+ """
56
+ Fit the NMF model to X (in FP32) and return the factorized matrices (W, H).
57
+
58
+ If GPU is available, attempts GPU-based factorization with CuPy.
59
+ Otherwise, falls back to CPU-based factorization with NumPy.
60
+ """
61
+ if gpu_available:
62
+ try:
63
+ return self._fit_transform_gpu(X)
64
+ except cp.cuda.memory.OutOfMemoryError:
65
+ print("GPU out of memory during NMF computation. Switching to CPU.")
66
+ return self._fit_transform_cpu(cp.asnumpy(X))
67
+ else:
68
+ return self._fit_transform_cpu(X)
69
+
70
+ def _fit_transform_gpu(self, X):
71
+ cp.random.seed(self.random_state)
72
+ X = cp.asarray(X, dtype=cp.float32)
73
+ n_samples, n_features = X.shape
74
+
75
+ W = cp.maximum(cp.random.rand(n_samples, self.n_components, dtype=cp.float32), 1e-4)
76
+ H = cp.maximum(cp.random.rand(self.n_components, n_features, dtype=cp.float32), 1e-4)
77
+
78
+ for _ in range(self.max_iter):
79
+ try:
80
+ numerator_H = W.T @ X
81
+ denominator_H = W.T @ W @ H + 1e-9
82
+ H *= numerator_H / denominator_H
83
+ H = cp.maximum(H, 1e-4)
84
+
85
+ numerator_W = X @ H.T
86
+ denominator_W = W @ H @ H.T + 1e-9
87
+ W *= numerator_W / denominator_W
88
+ W = cp.maximum(W, 1e-4)
89
+ except cp.cuda.memory.OutOfMemoryError:
90
+ print("GPU out of memory during NMF iteration. Switching to CPU.")
91
+ del W, H, X
92
+ cp._default_memory_pool.free_all_blocks()
93
+ return self._fit_transform_cpu(cp.asnumpy(X))
94
+ return W.get(), H.get()
95
+
96
+ def _fit_transform_cpu(self, X):
97
+ np.random.seed(self.random_state)
98
+ X = X.astype(np.float32)
99
+ n_samples, n_features = X.shape
100
+
101
+ W = np.maximum(np.random.rand(n_samples, self.n_components).astype(np.float32), 1e-4)
102
+ H = np.maximum(np.random.rand(self.n_components, n_features).astype(np.float32), 1e-4)
103
+
104
+ for _ in range(self.max_iter):
105
+ numerator_H = W.T @ X
106
+ denominator_H = W.T @ W @ H + 1e-9
107
+ H *= numerator_H / denominator_H
108
+ H = np.maximum(H, 1e-4)
109
+
110
+ numerator_W = X @ H.T
111
+ denominator_W = W @ H @ H.T + 1e-9
112
+ W *= numerator_W / denominator_W
113
+ W = np.maximum(W, 1e-4)
114
+ return W, H
115
+
116
+ class BenchMake:
117
+ FIXED_RANDOM_STATE = 42 # For any random operations in NMF, etc.
118
+
119
+ def __init__(self, n_jobs=-1):
120
+ """
121
+ Initialize BenchMake with the specified number of parallel jobs.
122
+ """
123
+ self.n_jobs = n_jobs
124
+
125
+ def _determine_batch_size(self, n_samples):
126
+ """
127
+ Automatically determine a batch size based on the number of samples and the number of jobs.
128
+ Aim for roughly 10 batches per worker; clamp the result between 100 and 1000.
129
+ """
130
+ p = self.n_jobs if self.n_jobs > 0 else (os.cpu_count() or 1)
131
+ batch_size = math.ceil(n_samples / (10 * p))
132
+ batch_size = max(100, min(batch_size, 1000))
133
+ return batch_size
134
+
135
+ def partition(self, X, y, test_size=0.2, data_type='tabular', return_indices=False):
136
+ """
137
+ Partition the dataset into training and testing sets via archetypal analysis
138
+ (with stable hashing) using FP32 throughout.
139
+
140
+ The only inputs required from the user are:
141
+ X, y, test_size, data_type, and return_indices.
142
+ Batch size is automatically determined.
143
+
144
+ Before GPU computations, the code estimates the required memory and checks
145
+ available GPU memory. If insufficient, it prints a warning and reverts to CPU.
146
+
147
+ If return_indices is False (default):
148
+ returns (X_train, X_test, y_train, y_test) in the same type as the inputs.
149
+ If return_indices is True:
150
+ returns (train_indices, test_indices) as lists of integers.
151
+ """
152
+ if data_type == 'tabular':
153
+ return self._partition_tabular(X, y, test_size, return_indices)
154
+ elif data_type == 'image':
155
+ return self._partition_image(X, y, test_size, return_indices)
156
+ elif data_type == 'sequential':
157
+ return self._partition_sequential(X, y, test_size, return_indices)
158
+ elif data_type == 'signal':
159
+ return self._partition_signal(X, y, test_size, return_indices)
160
+ elif data_type == 'graph':
161
+ return self._partition_graph(X, y, test_size, return_indices)
162
+ else:
163
+ raise ValueError(f"Unsupported data type: {data_type}")
164
+
165
+ # --- Partitioning methods for each data type ---
166
+
167
+ def _partition_tabular(self, X, y, test_size, return_indices):
168
+ if isinstance(X, pd.DataFrame):
169
+ X = X.values.astype(np.float32)
170
+ X_ordered, y_ordered = self._order_data_by_hash(X, y)
171
+ if gpu_available:
172
+ self._check_gpu_memory(X_ordered, test_size)
173
+ batch_size = self._determine_batch_size(len(X_ordered))
174
+ num_samples = len(X_ordered)
175
+ num_archetypes = max(1, int(np.ceil(num_samples * test_size)))
176
+ _, selected_indices = self._perform_archetypal_analysis(X_ordered, test_size, num_archetypes, batch_size)
177
+ return self._split_data(X_ordered, y_ordered, selected_indices, return_indices)
178
+
179
+ def _partition_image(self, X, y, test_size, return_indices):
180
+ if isinstance(X, pd.DataFrame):
181
+ X = X.values
182
+ if X.ndim >= 3:
183
+ n_samples = X.shape[0]
184
+ X = X.reshape(n_samples, -1).astype(np.float32)
185
+ elif X.ndim == 2:
186
+ X = X.astype(np.float32)
187
+ else:
188
+ raise ValueError("Unsupported image data shape.")
189
+ X_ordered, y_ordered = self._order_data_by_hash(X, y)
190
+ if gpu_available:
191
+ self._check_gpu_memory(X_ordered, test_size)
192
+ batch_size = self._determine_batch_size(len(X_ordered))
193
+ num_samples = len(X_ordered)
194
+ num_archetypes = max(1, int(np.ceil(num_samples * test_size)))
195
+ _, selected_indices = self._perform_archetypal_analysis(X_ordered, test_size, num_archetypes, batch_size)
196
+ return self._split_data(X_ordered, y_ordered, selected_indices, return_indices)
197
+
198
+ def _partition_signal(self, X, y, test_size, return_indices):
199
+ if isinstance(X, pd.DataFrame):
200
+ X = X.values
201
+ if isinstance(X, np.ndarray):
202
+ if X.ndim == 1:
203
+ X = X.reshape(-1, 1).astype(np.float32)
204
+ elif X.ndim > 2:
205
+ n_samples = X.shape[0]
206
+ X = X.reshape(n_samples, -1).astype(np.float32)
207
+ else:
208
+ X = X.astype(np.float32)
209
+ X_ordered, y_ordered = self._order_data_by_hash(X, y)
210
+ if gpu_available:
211
+ self._check_gpu_memory(X_ordered, test_size)
212
+ batch_size = self._determine_batch_size(len(X_ordered))
213
+ num_samples = len(X_ordered)
214
+ num_archetypes = max(1, int(np.ceil(num_samples * test_size)))
215
+ _, selected_indices = self._perform_archetypal_analysis(X_ordered, test_size, num_archetypes, batch_size)
216
+ return self._split_data(X_ordered, y_ordered, selected_indices, return_indices)
217
+
218
+ def _partition_sequential(self, X, y, test_size, return_indices):
219
+ if isinstance(X, pd.Series):
220
+ X_seq = X.tolist()
221
+ elif isinstance(X, list):
222
+ X_seq = X
223
+ else:
224
+ raise ValueError("Sequential data must be a list or Series.")
225
+ vectorizer = CountVectorizer(analyzer='char', lowercase=False)
226
+ X_numerical = vectorizer.fit_transform(X_seq).toarray().astype(np.float32)
227
+ X_ordered_num, y_ordered = self._order_data_by_hash(X_numerical, y)
228
+ if gpu_available:
229
+ self._check_gpu_memory(X_ordered_num, test_size)
230
+ batch_size = self._determine_batch_size(len(X_ordered_num))
231
+ num_samples = len(X_ordered_num)
232
+ num_archetypes = max(1, int(np.ceil(num_samples * test_size)))
233
+ _, selected_indices = self._perform_archetypal_analysis(X_ordered_num, test_size, num_archetypes, batch_size)
234
+ X_seq_ordered, _ = self._order_data_by_hash(X_seq, y)
235
+ return self._split_data(X_seq_ordered, y_ordered, selected_indices, return_indices)
236
+
237
+ def _partition_graph(self, X, y, test_size, return_indices):
238
+ if isinstance(X, pd.DataFrame):
239
+ X = X.values
240
+ if X.ndim > 2:
241
+ n_samples = X.shape[0]
242
+ X = X.reshape(n_samples, -1)
243
+ X = X.astype(np.float32)
244
+ X_ordered, y_ordered = self._order_data_by_hash(X, y)
245
+ if gpu_available:
246
+ self._check_gpu_memory(X_ordered, test_size)
247
+ batch_size = self._determine_batch_size(len(X_ordered))
248
+ num_samples = len(X_ordered)
249
+ num_archetypes = max(1, int(np.ceil(num_samples * test_size)))
250
+ _, selected_indices = self._perform_archetypal_analysis(X_ordered, test_size, num_archetypes, batch_size)
251
+ return self._split_data(X_ordered, y_ordered, selected_indices, return_indices)
252
+
253
+ # --- Archetypal Analysis and Distance Computations (FP32) ---
254
+
255
+ def _perform_archetypal_analysis(self, X, test_size, num_archetypes, batch_size=1000):
256
+ if isinstance(X, pd.DataFrame):
257
+ X = X.values
258
+ elif isinstance(X, list):
259
+ X = np.array(X, dtype=np.float32)
260
+ X = X.astype(np.float32)
261
+ X_min = np.min(X, axis=0).astype(np.float32)
262
+ X_max = np.max(X, axis=0).astype(np.float32)
263
+ X_scaled = (X - X_min) / (X_max - X_min + 1e-9)
264
+ X_scaled = X_scaled.astype(np.float32)
265
+ n_samples, n_features = X_scaled.shape
266
+ test_size_count = max(1, int(np.ceil(n_samples * test_size)))
267
+ num_archetypes = test_size_count
268
+ nmf = NMF(n_components=num_archetypes, max_iter=200, tol=1e-4, random_state=42)
269
+ W, H = nmf.fit_transform(X_scaled)
270
+ explained_variances = np.var(W, axis=0)
271
+ sorted_indices = np.argsort(explained_variances)[::-1]
272
+ H_sorted = H[sorted_indices]
273
+ distances = self._compute_distances(X_scaled, H_sorted, batch_size)
274
+ selected_indices = set()
275
+ for i in range(num_archetypes):
276
+ archetype_distances = distances[:, i].copy()
277
+ if selected_indices:
278
+ archetype_distances[list(selected_indices)] = np.inf
279
+ idx = np.argmin(archetype_distances)
280
+ selected_indices.add(idx)
281
+ selected_indices = sorted(selected_indices)
282
+ return X_scaled, selected_indices
283
+
284
+ def _compute_distances(self, X_scaled, H_sorted, batch_size=1000):
285
+ if gpu_available and cp is not None:
286
+ return self._compute_distances_gpu_batched(X_scaled, H_sorted, batch_size)
287
+ else:
288
+ return self._compute_distances_cpu_batched(X_scaled, H_sorted, batch_size)
289
+
290
+ def _compute_distances_gpu_batched(self, X_scaled, H_sorted, batch_size=1000):
291
+ n_samples = X_scaled.shape[0]
292
+ n_archetypes = H_sorted.shape[0]
293
+ distances = np.empty((n_samples, n_archetypes), dtype=np.float32)
294
+ try:
295
+ H_sorted_cp = cp.asarray(H_sorted, dtype=cp.float32)
296
+ for start_idx in range(0, n_samples, batch_size):
297
+ end_idx = min(start_idx + batch_size, n_samples)
298
+ X_batch = cp.asarray(X_scaled[start_idx:end_idx], dtype=cp.float32)
299
+ batch_distances = cp.linalg.norm(
300
+ X_batch[:, cp.newaxis, :] - H_sorted_cp[cp.newaxis, :, :],
301
+ axis=2
302
+ ).get()
303
+ distances[start_idx:end_idx] = batch_distances
304
+ del X_batch, batch_distances
305
+ cp._default_memory_pool.free_all_blocks()
306
+ del H_sorted_cp
307
+ cp._default_memory_pool.free_all_blocks()
308
+ except cp.cuda.memory.OutOfMemoryError:
309
+ print("GPU out of memory. Switching to CPU distance computation.")
310
+ cp._default_memory_pool.free_all_blocks()
311
+ return self._compute_distances_cpu_batched(X_scaled, H_sorted, batch_size)
312
+ return distances
313
+
314
+ def _compute_distances_cpu_batched(self, X_scaled, H_sorted, batch_size=500):
315
+ n_samples = X_scaled.shape[0]
316
+ n_archetypes = H_sorted.shape[0]
317
+ distances = np.empty((n_samples, n_archetypes), dtype=np.float32)
318
+ def compute_batch(start_idx, end_idx):
319
+ X_batch = X_scaled[start_idx:end_idx]
320
+ batch_distances = np.linalg.norm(
321
+ X_batch[:, np.newaxis, :] - H_sorted[np.newaxis, :, :],
322
+ axis=2
323
+ ).astype(np.float32)
324
+ return (start_idx, end_idx, batch_distances)
325
+ batches = [(i, min(i + batch_size, n_samples)) for i in range(0, n_samples, batch_size)]
326
+ results = Parallel(n_jobs=self.n_jobs)(delayed(compute_batch)(start, end) for start, end in batches)
327
+ for start, end, batch_distances in results:
328
+ distances[start:end] = batch_distances
329
+ return distances
330
+
331
+ # --- GPU Memory Estimation and Check ---
332
+
333
+ def _estimate_memory(self, X, test_size):
334
+ n_samples, n_features = X.shape
335
+ n_components = max(1, int(np.ceil(n_samples * test_size)))
336
+ size_X = n_samples * n_features * 4
337
+ size_W = n_samples * n_components * 4
338
+ size_H = n_components * n_features * 4
339
+ size_X_scaled = size_X
340
+ size_distance = n_samples * n_components * 4
341
+ total = size_X + size_W + size_H + size_X_scaled + size_distance
342
+ safety_factor = 1.5
343
+ return total * safety_factor
344
+
345
+ def _check_gpu_memory(self, X, test_size):
346
+ global gpu_available
347
+ estimated = self._estimate_memory(X, test_size)
348
+ free_mem = cp.cuda.runtime.memGetInfo()[0]
349
+ if free_mem < estimated:
350
+ print(f"Warning: Estimated GPU memory required is {estimated} bytes, "
351
+ f"but only {free_mem} bytes are free. Switching to CPU.")
352
+ gpu_available = False
353
+
354
+ # --- Hash-based ordering ---
355
+
356
+ def _order_data_by_hash(self, X, y):
357
+ row_hashes = []
358
+ num_rows = len(X)
359
+ for i in range(num_rows):
360
+ row_i = self._get_row(X, i)
361
+ row_bytes = self._row_to_bytes(row_i)
362
+ h = hashlib.md5(row_bytes).hexdigest()
363
+ row_hashes.append(h)
364
+ sorted_indices = np.argsort(row_hashes)
365
+ X_ordered = self._reindex_data(X, sorted_indices)
366
+ y_ordered = self._reindex_data(y, sorted_indices)
367
+ return X_ordered, y_ordered
368
+
369
+ def _get_row(self, X, i):
370
+ if isinstance(X, pd.DataFrame):
371
+ return X.iloc[i].values
372
+ elif isinstance(X, pd.Series):
373
+ return X.iloc[i]
374
+ elif isinstance(X, np.ndarray):
375
+ return X[i]
376
+ elif isinstance(X, list):
377
+ return X[i]
378
+ else:
379
+ raise TypeError("Unsupported type for X in _get_row().")
380
+
381
+ def _row_to_bytes(self, row_i):
382
+ if isinstance(row_i, str):
383
+ return row_i.encode('utf-8')
384
+ if isinstance(row_i, (np.ndarray, list, tuple)):
385
+ try:
386
+ arr = np.array(row_i, dtype=np.float32).reshape(-1)
387
+ return arr.tobytes()
388
+ except ValueError:
389
+ return str(row_i).encode('utf-8')
390
+ else:
391
+ return str(row_i).encode('utf-8')
392
+
393
+ def _reindex_data(self, data, indices):
394
+ if isinstance(data, pd.DataFrame):
395
+ return data.iloc[indices].reset_index(drop=True)
396
+ elif isinstance(data, pd.Series):
397
+ return data.iloc[indices].reset_index(drop=True)
398
+ elif isinstance(data, np.ndarray):
399
+ return data[indices]
400
+ elif isinstance(data, list):
401
+ return [data[i] for i in indices]
402
+ else:
403
+ raise TypeError("Unsupported data type in _reindex_data.")
404
+
405
+ # --- Splitting train/test with optional return of indices ---
406
+
407
+ def _split_data(self, X, y, selected_indices, return_indices):
408
+ test_set = set(selected_indices)
409
+ all_set = set(range(len(X)))
410
+ train_set = sorted(all_set - test_set)
411
+ test_set = sorted(test_set)
412
+ if len(test_set) == 0:
413
+ raise ValueError("No instances selected for the test set.")
414
+ if len(train_set) == 0:
415
+ raise ValueError("No instances left for the training set.")
416
+ if return_indices:
417
+ return train_set, test_set
418
+ else:
419
+ X_train = self._reindex_data(X, train_set)
420
+ X_test = self._reindex_data(X, test_set)
421
+ y_train = self._reindex_data(y, train_set)
422
+ y_test = self._reindex_data(y, test_set)
423
+ return X_train, X_test, y_train, y_test
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) [2025] Amanda S Barnard
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.