matrix-compute-node 0.1.0__py3-none-any.whl

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,409 @@
1
+ """Math Acceleration Compute Engine for matrix-compute-node."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import hashlib
6
+ import logging
7
+ from typing import Optional, Tuple
8
+
9
+ import numpy as np
10
+
11
+ logger = logging.getLogger(__name__)
12
+
13
+ # Try importing hardware acceleration backends
14
+ _TORCH_AVAILABLE = False
15
+ _CUDA_AVAILABLE = False
16
+ try:
17
+ import torch
18
+ _TORCH_AVAILABLE = True
19
+ _CUDA_AVAILABLE = torch.cuda.is_available()
20
+ except ImportError:
21
+ pass
22
+
23
+ _CUPY_AVAILABLE = False
24
+ try:
25
+ import cupy
26
+ _CUPY_AVAILABLE = True
27
+ except ImportError:
28
+ pass
29
+
30
+
31
+ class ComputeEngine:
32
+ """
33
+ High-performance block matrix multiplication (GEMM) acceleration engine.
34
+ Supports PyTorch (CUDA / CPU), CuPy (CUDA), and NumPy fallback.
35
+ """
36
+
37
+ def __init__(self, prefer_gpu: bool = True, force_cpu: bool = False) -> None:
38
+ self.prefer_gpu = prefer_gpu and not force_cpu
39
+ self.backend = self._determine_backend()
40
+
41
+ def _determine_backend(self) -> str:
42
+ if self.prefer_gpu and _TORCH_AVAILABLE and _CUDA_AVAILABLE:
43
+ return "torch_cuda"
44
+ if self.prefer_gpu and _CUPY_AVAILABLE:
45
+ return "cupy"
46
+ if _TORCH_AVAILABLE and not self.prefer_gpu:
47
+ return "torch_cpu"
48
+ return "numpy"
49
+
50
+ def gemm(self, a: np.ndarray, b: np.ndarray, dtype: str = "fp32") -> np.ndarray:
51
+ """
52
+ Calculates C = A x B for the specified precision datatype.
53
+ Supported dtypes: 'fp32', 'fp16', 'bf16'.
54
+ """
55
+ if a.ndim != 2 or b.ndim != 2:
56
+ raise ValueError(f"Matrices must be 2-dimensional. Got shapes {a.shape} and {b.shape}")
57
+
58
+ if a.shape[1] != b.shape[0]:
59
+ raise ValueError(
60
+ f"Inner dimension mismatch: A columns ({a.shape[1]}) != B rows ({b.shape[0]})"
61
+ )
62
+
63
+ norm_dtype = dtype.lower().strip()
64
+ if norm_dtype not in ("fp32", "fp16", "bf16"):
65
+ raise ValueError(f"Unsupported dtype '{dtype}'. Supported: 'fp32', 'fp16', 'bf16'")
66
+
67
+ # Execute using determined backend
68
+ if self.backend == "torch_cuda" and _TORCH_AVAILABLE:
69
+ try:
70
+ torch_dtype = torch.float32
71
+ if norm_dtype == "fp16":
72
+ torch_dtype = torch.float16
73
+ elif norm_dtype == "bf16":
74
+ torch_dtype = torch.bfloat16
75
+
76
+ t_a = torch.from_numpy(np.ascontiguousarray(a)).to(device="cuda", dtype=torch_dtype)
77
+ t_b = torch.from_numpy(np.ascontiguousarray(b)).to(device="cuda", dtype=torch_dtype)
78
+ t_c = torch.matmul(t_a, t_b)
79
+ if norm_dtype == "bf16":
80
+ return ComputeEngine.truncate_to_bf16(t_c.to(torch.float32).cpu().numpy())
81
+ c = t_c.cpu().numpy()
82
+ return c
83
+ except Exception as ex:
84
+ logger.warning(f"CUDA PyTorch GEMM failed, falling back to NumPy: {ex}")
85
+
86
+ if self.backend == "cupy" and _CUPY_AVAILABLE:
87
+ try:
88
+ cp_a = cupy.asarray(a)
89
+ cp_b = cupy.asarray(b)
90
+ if norm_dtype == "bf16":
91
+ cp_a = cupy.asarray(ComputeEngine.truncate_to_bf16(a), dtype=cupy.float32)
92
+ cp_b = cupy.asarray(ComputeEngine.truncate_to_bf16(b), dtype=cupy.float32)
93
+ cp_c = cupy.matmul(cp_a, cp_b)
94
+ return ComputeEngine.truncate_to_bf16(cupy.asnumpy(cp_c))
95
+ elif norm_dtype == "fp16":
96
+ cp_c = cupy.matmul(cp_a.astype(cupy.float16), cp_b.astype(cupy.float16))
97
+ return cupy.asnumpy(cp_c)
98
+ else:
99
+ cp_c = cupy.matmul(cp_a.astype(cupy.float32), cp_b.astype(cupy.float32))
100
+ return cupy.asnumpy(cp_c)
101
+ except Exception as ex:
102
+ logger.warning(f"CuPy GEMM failed, falling back to NumPy: {ex}")
103
+
104
+ # NumPy CPU Fallback
105
+ if norm_dtype == "bf16":
106
+ # True BF16 emulation via 16-bit float32 mantissa masking
107
+ a_bf16 = ComputeEngine.truncate_to_bf16(a)
108
+ b_bf16 = ComputeEngine.truncate_to_bf16(b)
109
+ c = np.matmul(a_bf16.astype(np.float64), b_bf16.astype(np.float64)).astype(np.float32)
110
+ return ComputeEngine.truncate_to_bf16(c)
111
+
112
+ a_f64 = a.astype(np.float64)
113
+ b_f64 = b.astype(np.float64)
114
+ c_f64 = np.matmul(a_f64, b_f64)
115
+
116
+ if norm_dtype == "fp32":
117
+ return c_f64.astype(np.float32)
118
+ elif norm_dtype == "fp16":
119
+ return c_f64.astype(np.float16)
120
+
121
+ return c_f64.astype(np.float32)
122
+
123
+ def gemv(self, a: np.ndarray, v: np.ndarray, dtype: str = "fp32") -> np.ndarray:
124
+ """
125
+ Calculates matrix-vector product v_next = A x v for the specified precision datatype.
126
+ Supports 1D vector v of shape (K,) and 2D column vector v of shape (K, 1).
127
+ Always returns 1D array of shape (M,).
128
+
129
+ Supported dtypes: 'fp32', 'fp16', 'bf16'.
130
+ """
131
+ if not isinstance(a, np.ndarray):
132
+ a = np.asarray(a)
133
+ if not isinstance(v, np.ndarray):
134
+ v = np.asarray(v)
135
+
136
+ if a.ndim != 2:
137
+ raise ValueError(f"Matrix A must be 2-dimensional. Got shape {a.shape}")
138
+
139
+ if v.ndim == 1:
140
+ if v.shape[0] != a.shape[1]:
141
+ raise ValueError(
142
+ f"Inner dimension mismatch: A columns ({a.shape[1]}) != V elements ({v.shape[0]})"
143
+ )
144
+ v_1d = np.ascontiguousarray(v)
145
+ elif v.ndim == 2:
146
+ if v.shape[1] != 1:
147
+ raise ValueError(
148
+ f"Vector V must be 1D or 2D column vector (shape (K,) or (K, 1)). Got shape {v.shape}"
149
+ )
150
+ if v.shape[0] != a.shape[1]:
151
+ raise ValueError(
152
+ f"Inner dimension mismatch: A columns ({a.shape[1]}) != V rows ({v.shape[0]})"
153
+ )
154
+ v_1d = np.ascontiguousarray(v.reshape(-1))
155
+ else:
156
+ raise ValueError(
157
+ f"Vector V must be 1D or 2D column vector (shape (K,) or (K, 1)). Got shape {v.shape}"
158
+ )
159
+
160
+ norm_dtype = dtype.lower().strip()
161
+ if norm_dtype in ("float32", "fp32"):
162
+ norm_dtype = "fp32"
163
+ elif norm_dtype in ("float16", "fp16"):
164
+ norm_dtype = "fp16"
165
+ elif norm_dtype in ("bfloat16", "bf16"):
166
+ norm_dtype = "bf16"
167
+ else:
168
+ raise ValueError(f"Unsupported dtype '{dtype}'. Supported: 'fp32', 'fp16', 'bf16'")
169
+
170
+ # Backend: PyTorch CUDA
171
+ if self.backend == "torch_cuda" and _TORCH_AVAILABLE:
172
+ try:
173
+ torch_dtype = torch.float32
174
+ if norm_dtype == "fp16":
175
+ torch_dtype = torch.float16
176
+ elif norm_dtype == "bf16":
177
+ torch_dtype = torch.bfloat16
178
+
179
+ t_a = torch.from_numpy(np.ascontiguousarray(a)).to(device="cuda", dtype=torch_dtype)
180
+ t_v = torch.from_numpy(v_1d).to(device="cuda", dtype=torch_dtype)
181
+ t_res = torch.mv(t_a, t_v)
182
+
183
+ if norm_dtype == "bf16":
184
+ res_np = t_res.to(torch.float32).cpu().numpy()
185
+ return ComputeEngine.truncate_to_bf16(res_np).reshape(-1)
186
+
187
+ res_np = t_res.cpu().numpy()
188
+ if norm_dtype == "fp16":
189
+ return res_np.astype(np.float16).reshape(-1)
190
+ return res_np.astype(np.float32).reshape(-1)
191
+ except Exception as ex:
192
+ logger.warning(f"CUDA PyTorch GEMV failed, falling back to NumPy: {ex}")
193
+
194
+ # Backend: CuPy
195
+ if self.backend == "cupy" and _CUPY_AVAILABLE:
196
+ try:
197
+ cp_a = cupy.asarray(a)
198
+ cp_v = cupy.asarray(v_1d)
199
+ if norm_dtype == "bf16":
200
+ cp_a = cupy.asarray(ComputeEngine.truncate_to_bf16(a), dtype=cupy.float32)
201
+ cp_v = cupy.asarray(ComputeEngine.truncate_to_bf16(v_1d), dtype=cupy.float32)
202
+ cp_res = cupy.matmul(cp_a, cp_v)
203
+ return ComputeEngine.truncate_to_bf16(cupy.asnumpy(cp_res)).reshape(-1)
204
+ elif norm_dtype == "fp16":
205
+ cp_res = cupy.matmul(cp_a.astype(cupy.float16), cp_v.astype(cupy.float16))
206
+ return cupy.asnumpy(cp_res).astype(np.float16).reshape(-1)
207
+ else:
208
+ cp_res = cupy.matmul(cp_a.astype(cupy.float32), cp_v.astype(cupy.float32))
209
+ return cupy.asnumpy(cp_res).astype(np.float32).reshape(-1)
210
+ except Exception as ex:
211
+ logger.warning(f"CuPy GEMV failed, falling back to NumPy: {ex}")
212
+
213
+ # Backend: PyTorch CPU
214
+ if self.backend == "torch_cpu" and _TORCH_AVAILABLE:
215
+ try:
216
+ torch_dtype = torch.float32
217
+ if norm_dtype == "fp16":
218
+ torch_dtype = torch.float16
219
+ elif norm_dtype == "bf16":
220
+ torch_dtype = torch.bfloat16
221
+
222
+ t_a = torch.from_numpy(np.ascontiguousarray(a)).to(dtype=torch_dtype)
223
+ t_v = torch.from_numpy(v_1d).to(dtype=torch_dtype)
224
+ t_res = torch.mv(t_a, t_v)
225
+
226
+ if norm_dtype == "bf16":
227
+ return ComputeEngine.truncate_to_bf16(t_res.to(torch.float32).numpy()).reshape(-1)
228
+ res_np = t_res.numpy()
229
+ if norm_dtype == "fp16":
230
+ return res_np.astype(np.float16).reshape(-1)
231
+ return res_np.astype(np.float32).reshape(-1)
232
+ except Exception as ex:
233
+ logger.warning(f"PyTorch CPU GEMV failed, falling back to NumPy: {ex}")
234
+
235
+ # Backend: NumPy CPU Fallback
236
+ if norm_dtype == "bf16":
237
+ a_bf16 = ComputeEngine.truncate_to_bf16(a)
238
+ v_bf16 = ComputeEngine.truncate_to_bf16(v_1d)
239
+ res = np.matmul(a_bf16.astype(np.float64), v_bf16.astype(np.float64)).astype(np.float32)
240
+ return ComputeEngine.truncate_to_bf16(res).reshape(-1)
241
+
242
+ a_f64 = a.astype(np.float64)
243
+ v_f64 = v_1d.astype(np.float64)
244
+ res_f64 = np.matmul(a_f64, v_f64)
245
+
246
+ if norm_dtype == "fp32":
247
+ return res_f64.astype(np.float32).reshape(-1)
248
+ elif norm_dtype == "fp16":
249
+ return res_f64.astype(np.float16).reshape(-1)
250
+
251
+ return res_f64.astype(np.float32).reshape(-1)
252
+
253
+ @staticmethod
254
+ def truncate_to_bf16(tensor: np.ndarray) -> np.ndarray:
255
+ """
256
+ Truncates / masks float32 mantissa to 7 bits (IEEE bfloat16 emulation).
257
+ Clears the lowest 16 bits of 32-bit float representation.
258
+ Guarantees contiguous memory layout, preserves NaN/Inf semantics, signed zeros,
259
+ and subnormal underflow characteristics.
260
+ """
261
+ f32 = np.ascontiguousarray(tensor, dtype=np.float32)
262
+ u32 = f32.view(np.uint32)
263
+ masked_u32 = u32 & np.uint32(0xFFFF0000)
264
+
265
+ # Preserve NaN semantics: if input was NaN and lower-16-bit truncation cleared
266
+ # the entire mantissa to 0 (which would otherwise falsely convert NaN to Infinity),
267
+ # restore the quiet NaN bit (bit 22, 0x00400000).
268
+ is_nan = np.isnan(f32)
269
+ if np.any(is_nan):
270
+ lost_mantissa = is_nan & ((masked_u32 & np.uint32(0x007F0000)) == 0)
271
+ if np.any(lost_mantissa):
272
+ masked_u32 = masked_u32.copy()
273
+ masked_u32[lost_mantissa] |= np.uint32(0x00400000)
274
+
275
+ return masked_u32.view(np.float32)
276
+
277
+ @staticmethod
278
+ def get_unit_roundoff(dtype: str = "fp32") -> float:
279
+ """Returns IEEE 754 unit roundoff u for given precision."""
280
+ dt = str(dtype).lower().strip()
281
+ if dt in ("fp16", "float16"):
282
+ return 2.0 ** -11 # ~4.8828e-4
283
+ elif dt in ("bf16", "bfloat16"):
284
+ return 2.0 ** -8 # ~3.90625e-3
285
+ elif dt in ("fp64", "float64"):
286
+ return 2.0 ** -53 # ~1.1102e-16
287
+ else:
288
+ return 2.0 ** -24 # ~5.9605e-8 (fp32)
289
+
290
+ @staticmethod
291
+ def higham_matrix_bound(k: int, norm_a: float, norm_b: float, dtype: str = "fp32") -> float:
292
+ """
293
+ Higham's matrix multiplication rounding bound:
294
+ gamma_K = (K * u) / (1 - K * u)
295
+ bound = gamma_K * ||A||_inf * ||B||_inf
296
+ """
297
+ u = ComputeEngine.get_unit_roundoff(dtype)
298
+ ku = float(k) * u
299
+ gamma_k = (ku / (1.0 - ku)) if ku < 0.999 else (ku * 1000.0)
300
+ return gamma_k * float(norm_a) * float(norm_b)
301
+
302
+ @staticmethod
303
+ def higham_vector_bound(k: int, norm_a: float, norm_v: float, dtype: str = "fp32") -> float:
304
+ """
305
+ Higham's matrix-vector rounding bound:
306
+ gamma_K = (K * u) / (1 - K * u)
307
+ bound = gamma_K * ||A||_inf * ||v||_inf
308
+ """
309
+ return ComputeEngine.higham_matrix_bound(k, norm_a, norm_v, dtype=dtype)
310
+
311
+ @staticmethod
312
+ def compute_sha256(tensor: np.ndarray) -> str:
313
+ """Computes SHA256 hex digest over raw contiguous bytes of tensor."""
314
+ if not tensor.flags["C_CONTIGUOUS"]:
315
+ tensor = np.ascontiguousarray(tensor)
316
+ return hashlib.sha256(tensor.tobytes()).hexdigest()
317
+
318
+ @staticmethod
319
+ def verify_freivalds(
320
+ a: np.ndarray,
321
+ b: np.ndarray,
322
+ c: np.ndarray,
323
+ epsilon: Optional[float] = None,
324
+ num_trials: int = 5,
325
+ dtype: Optional[str] = None,
326
+ ) -> Tuple[bool, float]:
327
+ """
328
+ Randomized Freivalds algorithm verification with Higham's dynamic scale-aware bound:
329
+ Computes gamma_K = (K * u) / (1 - K * u) scaled by ||A||_inf * ||B||_inf.
330
+ Evaluates both absolute discrepancy and relative discrepancy to defend against
331
+ false positives and zero-work fraud on small-magnitude inputs.
332
+ """
333
+ # Validate matrix shapes
334
+ if a.ndim != 2 or b.ndim != 2 or c.ndim != 2:
335
+ return False, float("inf")
336
+ if a.shape[1] != b.shape[0] or c.shape != (a.shape[0], b.shape[1]):
337
+ return False, float("inf")
338
+
339
+ # Guard against NaN/Inf in inputs or outputs (fraudulent or corrupted computation)
340
+ if not (np.all(np.isfinite(a)) and np.all(np.isfinite(b)) and np.all(np.isfinite(c))):
341
+ return False, float("inf")
342
+
343
+ n = b.shape[1]
344
+ k = a.shape[1]
345
+
346
+ # Determine precision datatype
347
+ if dtype is None:
348
+ if a.dtype == np.float16 or c.dtype == np.float16:
349
+ dtype = "fp16"
350
+ elif a.dtype == np.float64 or c.dtype == np.float64:
351
+ dtype = "fp64"
352
+ else:
353
+ dtype = "fp32"
354
+
355
+ u = ComputeEngine.get_unit_roundoff(dtype)
356
+ ku = float(k) * u
357
+ gamma_k = (ku / (1.0 - ku)) if ku < 0.999 else (ku * 1000.0)
358
+
359
+ # Calculate input infinity norms (maximum absolute row sum)
360
+ norm_a = float(np.linalg.norm(a, ord=np.inf))
361
+ norm_b = float(np.linalg.norm(b, ord=np.inf))
362
+ scale = norm_a * norm_b
363
+
364
+ # Dynamic scale-aware error bound
365
+ dynamic_bound = gamma_k * scale
366
+
367
+ max_discrepancy = 0.0
368
+
369
+ for _ in range(num_trials):
370
+ r = np.random.randint(0, 2, size=(n, 1)).astype(np.float64)
371
+ if not np.any(r):
372
+ r[np.random.randint(0, n), 0] = 1.0
373
+ br = np.matmul(b.astype(np.float64), r)
374
+ abr = np.matmul(a.astype(np.float64), br)
375
+ cr = np.matmul(c.astype(np.float64), r)
376
+ diff = float(np.max(np.abs(abr - cr)))
377
+ if np.isnan(diff) or np.isinf(diff):
378
+ return False, float("inf")
379
+ if diff > max_discrepancy:
380
+ max_discrepancy = diff
381
+
382
+ # Check relative discrepancy against gamma_k to catch zero-work fraud on small inputs
383
+ abr_norm = float(np.max(np.abs(abr)))
384
+ cr_norm = float(np.max(np.abs(cr)))
385
+ denom = max(scale, abr_norm, cr_norm)
386
+
387
+ # If inputs are non-zero:
388
+ if denom > 0.0:
389
+ rel_diff = diff / denom
390
+ # Relative discrepancy check prevents zero-work fraud
391
+ allowed_rel = max(gamma_k, epsilon if epsilon is not None else 0.0, 1e-7)
392
+ if rel_diff > allowed_rel:
393
+ return False, max_discrepancy
394
+
395
+ # Absolute bound check scaled by input norms (never tighter than physical rounding bound)
396
+ effective_bound = dynamic_bound
397
+ if epsilon is not None and scale >= 1.0:
398
+ effective_bound = max(dynamic_bound, epsilon)
399
+ elif epsilon is not None:
400
+ effective_bound = max(dynamic_bound, epsilon * scale)
401
+
402
+ if diff > effective_bound:
403
+ return False, max_discrepancy
404
+ else:
405
+ # Scale is zero (A=0 or B=0) -> A*B is 0. C must be near 0.
406
+ if diff > 1e-7:
407
+ return False, max_discrepancy
408
+
409
+ return True, max_discrepancy