laakhay-quantlab 0.0.1__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.
Files changed (73) hide show
  1. laakhay_quantlab-0.0.1/.gitignore +20 -0
  2. laakhay_quantlab-0.0.1/LICENSE +21 -0
  3. laakhay_quantlab-0.0.1/PKG-INFO +110 -0
  4. laakhay_quantlab-0.0.1/README.md +65 -0
  5. laakhay_quantlab-0.0.1/laakhay/quantlab/__init__.py +6 -0
  6. laakhay_quantlab-0.0.1/laakhay/quantlab/backend/__init__.py +81 -0
  7. laakhay_quantlab-0.0.1/laakhay/quantlab/backend/backend.py +163 -0
  8. laakhay_quantlab-0.0.1/laakhay/quantlab/backend/device.py +57 -0
  9. laakhay_quantlab-0.0.1/laakhay/quantlab/backend/implementations/__init__.py +27 -0
  10. laakhay_quantlab-0.0.1/laakhay/quantlab/backend/implementations/fallback.py +47 -0
  11. laakhay_quantlab-0.0.1/laakhay/quantlab/backend/implementations/jax.py +174 -0
  12. laakhay_quantlab-0.0.1/laakhay/quantlab/backend/implementations/numpy.py +349 -0
  13. laakhay_quantlab-0.0.1/laakhay/quantlab/backend/implementations/torch.py +364 -0
  14. laakhay_quantlab-0.0.1/laakhay/quantlab/backend/interface.py +268 -0
  15. laakhay_quantlab-0.0.1/laakhay/quantlab/backend/ops.py +140 -0
  16. laakhay_quantlab-0.0.1/laakhay/quantlab/backend/registry.py +88 -0
  17. laakhay_quantlab-0.0.1/laakhay/quantlab/backtest/__init__.py +42 -0
  18. laakhay_quantlab-0.0.1/laakhay/quantlab/backtest/config.py +92 -0
  19. laakhay_quantlab-0.0.1/laakhay/quantlab/backtest/engine/__init__.py +3 -0
  20. laakhay_quantlab-0.0.1/laakhay/quantlab/backtest/engine/core.py +1012 -0
  21. laakhay_quantlab-0.0.1/laakhay/quantlab/backtest/engine/oms.py +135 -0
  22. laakhay_quantlab-0.0.1/laakhay/quantlab/backtest/engine/sizer.py +64 -0
  23. laakhay_quantlab-0.0.1/laakhay/quantlab/backtest/feed.py +90 -0
  24. laakhay_quantlab-0.0.1/laakhay/quantlab/backtest/metrics/__init__.py +23 -0
  25. laakhay_quantlab-0.0.1/laakhay/quantlab/backtest/metrics/performance.py +156 -0
  26. laakhay_quantlab-0.0.1/laakhay/quantlab/backtest/metrics/timeframe.py +32 -0
  27. laakhay_quantlab-0.0.1/laakhay/quantlab/backtest/metrics/trades.py +90 -0
  28. laakhay_quantlab-0.0.1/laakhay/quantlab/backtest/models/__init__.py +19 -0
  29. laakhay_quantlab-0.0.1/laakhay/quantlab/backtest/models/order.py +56 -0
  30. laakhay_quantlab-0.0.1/laakhay/quantlab/backtest/models/position.py +107 -0
  31. laakhay_quantlab-0.0.1/laakhay/quantlab/backtest/models/signal.py +27 -0
  32. laakhay_quantlab-0.0.1/laakhay/quantlab/backtest/models/trade.py +23 -0
  33. laakhay_quantlab-0.0.1/laakhay/quantlab/backtest/strategy/__init__.py +3 -0
  34. laakhay_quantlab-0.0.1/laakhay/quantlab/backtest/strategy/base.py +131 -0
  35. laakhay_quantlab-0.0.1/laakhay/quantlab/exceptions/__init__.py +33 -0
  36. laakhay_quantlab-0.0.1/laakhay/quantlab/pricing/__init__.py +65 -0
  37. laakhay_quantlab-0.0.1/laakhay/quantlab/pricing/greeks.py +171 -0
  38. laakhay_quantlab-0.0.1/laakhay/quantlab/pricing/market.py +83 -0
  39. laakhay_quantlab-0.0.1/laakhay/quantlab/pricing/options/__init__.py +75 -0
  40. laakhay_quantlab-0.0.1/laakhay/quantlab/pricing/options/asian.py +94 -0
  41. laakhay_quantlab-0.0.1/laakhay/quantlab/pricing/options/barrier.py +158 -0
  42. laakhay_quantlab-0.0.1/laakhay/quantlab/pricing/options/base.py +254 -0
  43. laakhay_quantlab-0.0.1/laakhay/quantlab/pricing/options/contracts.py +54 -0
  44. laakhay_quantlab-0.0.1/laakhay/quantlab/pricing/options/digital.py +60 -0
  45. laakhay_quantlab-0.0.1/laakhay/quantlab/pricing/options/strategies.py +250 -0
  46. laakhay_quantlab-0.0.1/laakhay/quantlab/pricing/pricers/__init__.py +8 -0
  47. laakhay_quantlab-0.0.1/laakhay/quantlab/pricing/pricers/black_scholes/__init__.py +189 -0
  48. laakhay_quantlab-0.0.1/laakhay/quantlab/pricing/pricers/black_scholes/calculations.py +140 -0
  49. laakhay_quantlab-0.0.1/laakhay/quantlab/pricing/pricers/black_scholes/formulas/asian.py +180 -0
  50. laakhay_quantlab-0.0.1/laakhay/quantlab/pricing/pricers/black_scholes/formulas/barrier.py +93 -0
  51. laakhay_quantlab-0.0.1/laakhay/quantlab/pricing/pricers/black_scholes/formulas/digital.py +182 -0
  52. laakhay_quantlab-0.0.1/laakhay/quantlab/pricing/pricers/black_scholes/formulas/european.py +132 -0
  53. laakhay_quantlab-0.0.1/laakhay/quantlab/pricing/pricers/black_scholes/registry.py +120 -0
  54. laakhay_quantlab-0.0.1/laakhay/quantlab/pricing/pricers/greeks/__init__.py +6 -0
  55. laakhay_quantlab-0.0.1/laakhay/quantlab/pricing/pricers/greeks/base.py +125 -0
  56. laakhay_quantlab-0.0.1/laakhay/quantlab/pricing/pricers/greeks/engine.py +175 -0
  57. laakhay_quantlab-0.0.1/laakhay/quantlab/pricing/pricers/greeks/finite_diff.py +151 -0
  58. laakhay_quantlab-0.0.1/laakhay/quantlab/pricing/pricers/greeks/utils.py +53 -0
  59. laakhay_quantlab-0.0.1/laakhay/quantlab/pricing/pricers/monte_carlo.py +113 -0
  60. laakhay_quantlab-0.0.1/laakhay/quantlab/pricing/pricers/pricer.py +71 -0
  61. laakhay_quantlab-0.0.1/laakhay/quantlab/pricing/simulations/base.py +53 -0
  62. laakhay_quantlab-0.0.1/laakhay/quantlab/pricing/simulations/models.py +123 -0
  63. laakhay_quantlab-0.0.1/laakhay/quantlab/pricing/simulations/samplers.py +44 -0
  64. laakhay_quantlab-0.0.1/laakhay/quantlab/pricing/utils.py +30 -0
  65. laakhay_quantlab-0.0.1/laakhay/quantlab/simulations/__init__.py +10 -0
  66. laakhay_quantlab-0.0.1/laakhay/quantlab/simulations/gbm.py +267 -0
  67. laakhay_quantlab-0.0.1/laakhay/quantlab/simulations/samplers/__init__.py +9 -0
  68. laakhay_quantlab-0.0.1/laakhay/quantlab/simulations/samplers/base.py +225 -0
  69. laakhay_quantlab-0.0.1/laakhay/quantlab/simulations/samplers/gaussian.py +153 -0
  70. laakhay_quantlab-0.0.1/laakhay/quantlab/types/__init__.py +37 -0
  71. laakhay_quantlab-0.0.1/laakhay/quantlab/types/backend.py +10 -0
  72. laakhay_quantlab-0.0.1/laakhay/quantlab/types/base.py +57 -0
  73. laakhay_quantlab-0.0.1/pyproject.toml +158 -0
@@ -0,0 +1,20 @@
1
+ venv/
2
+ .venv/
3
+
4
+ *.egg-info/
5
+
6
+ **/__pycache__/
7
+ **/.DS_Store
8
+
9
+ .env*
10
+
11
+ .claude/
12
+ .pytest_cache/
13
+ .ruff_cache/
14
+ .coverage*
15
+
16
+ quantlab/_version.py
17
+
18
+ htmlcov/
19
+ uv.lock
20
+
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2024 Laakhay
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,110 @@
1
+ Metadata-Version: 2.4
2
+ Name: laakhay-quantlab
3
+ Version: 0.0.1
4
+ Summary: Quant tools built with ♥︎ by Laakhay
5
+ Project-URL: Homepage, https://laakhay.com
6
+ Project-URL: Repository, https://github.com/laakhay/quantlab
7
+ Author-email: Laakhay Corporation <laakhay.corp@gmail.com>
8
+ License-Expression: MIT
9
+ License-File: LICENSE
10
+ Keywords: backtesting,finance,quantitative-analysis,trading
11
+ Classifier: Development Status :: 3 - Alpha
12
+ Classifier: Intended Audience :: Developers
13
+ Classifier: Intended Audience :: Financial and Insurance Industry
14
+ Classifier: Programming Language :: Python :: 3.12
15
+ Classifier: Programming Language :: Python :: 3.13
16
+ Classifier: Topic :: Office/Business :: Financial
17
+ Requires-Python: >=3.12
18
+ Requires-Dist: laakhay-data
19
+ Requires-Dist: laakhay-ta
20
+ Provides-Extra: all
21
+ Requires-Dist: jax[cpu]>=0.4.0; extra == 'all'
22
+ Requires-Dist: numpy>=1.21.0; extra == 'all'
23
+ Requires-Dist: scipy>=1.10.0; extra == 'all'
24
+ Requires-Dist: torch>=2.0.0; extra == 'all'
25
+ Provides-Extra: dev
26
+ Requires-Dist: build>=1.0; extra == 'dev'
27
+ Requires-Dist: mypy>=1.0.0; extra == 'dev'
28
+ Requires-Dist: numpy>=1.21.0; extra == 'dev'
29
+ Requires-Dist: pytest-asyncio>=0.24.0; extra == 'dev'
30
+ Requires-Dist: pytest-cov>=4.0.0; extra == 'dev'
31
+ Requires-Dist: pytest>=8.0; extra == 'dev'
32
+ Requires-Dist: ruff>=0.4; extra == 'dev'
33
+ Requires-Dist: scipy>=1.10.0; extra == 'dev'
34
+ Requires-Dist: twine>=5.0; extra == 'dev'
35
+ Provides-Extra: jax
36
+ Requires-Dist: jax[cpu]>=0.4.0; extra == 'jax'
37
+ Provides-Extra: jax-gpu
38
+ Requires-Dist: jax[cuda]>=0.4.0; extra == 'jax-gpu'
39
+ Provides-Extra: numpy
40
+ Requires-Dist: numpy>=1.21.0; extra == 'numpy'
41
+ Requires-Dist: scipy>=1.10.0; extra == 'numpy'
42
+ Provides-Extra: torch
43
+ Requires-Dist: torch>=2.0.0; extra == 'torch'
44
+ Description-Content-Type: text/markdown
45
+
46
+ # Laakhay Quantlab
47
+
48
+ `laakhay-quantlab` is a high-performance, backend-agnostic quantitative computation layer designed for simulation-heavy research and production analytics. It provides a unified interface over **NumPy**, **JAX**, and **PyTorch**, enabling seamless switching between CPU and GPU backends without code changes.
49
+
50
+ ## Key Features
51
+
52
+ - **Backend Agnostic**: Write once, run on NumPy, JAX, or PyTorch.
53
+ - **Hardware Acceleration**: Transparent GPU/TPU support via JAX/Torch backends.
54
+ - **Vectorized Operations**: Optimized `ArrayBackend` with JIT compilation support.
55
+ - **Simulation Primitives**: Fast Gaussian sampling, Geometric Brownian Motion (GBM), and more.
56
+ - **Options & Pricing (New)**: Comprehensive verification and pricing of derivatives using analytical (Black-Scholes) and numerical (Monte Carlo) methods.
57
+
58
+ ## Ecosystem
59
+
60
+ `laakhay-quantlab` fits into the broader Laakhay quantitative ecosystem:
61
+ 1. **`laakhay-data`**: Market data acquisition and normalization.
62
+ 2. **`laakhay-ta`**: Technical analysis indicators and strategy engine.
63
+ 3. **`laakhay-quantlab`**: Numerical simulation, pricing, and risk modeling.
64
+
65
+ ## Installation
66
+
67
+ ```bash
68
+ pip install laakhay-quantlab
69
+ # extensions: [jax, jax-gpu, torch, all]
70
+ pip install "laakhay-quantlab[all]"
71
+ ```
72
+
73
+ ## Quick Start: Options Pricing
74
+
75
+ The `pricing` module supports a wide range of exotic and vanilla options, along with Greeks calculation.
76
+
77
+ ```python
78
+ from laakhay.quantlab.pricing import (
79
+ EuropeanCall,
80
+ MarketData,
81
+ Pricer,
82
+ PricingMethod
83
+ )
84
+
85
+ # 1. Define Market Conditions
86
+ market = MarketData(spot=100.0, rate=0.05, vol=0.2)
87
+
88
+ # 2. Define Instrument
89
+ option = EuropeanCall(strike=100.0, expiry=1.0)
90
+
91
+ # 3. Price using Black-Scholes (Analytical)
92
+ bs_pricer = Pricer(method=PricingMethod.BLACK_SCHOLES)
93
+ price, greeks = bs_pricer.price_with_greeks(option, market)
94
+
95
+ print(f"Price: {price:.4f}")
96
+ print(f"Delta: {greeks.delta:.4f}")
97
+
98
+ # 4. Price using Monte Carlo (Numerical)
99
+ mc_pricer = Pricer(method=PricingMethod.MONTE_CARLO)
100
+ mc_price = mc_pricer.price(option, market)
101
+
102
+ print(f"MC Price: {mc_price:.4f}")
103
+ ```
104
+
105
+ ## Documentation
106
+
107
+ See the `docs/` directory for detailed guides:
108
+ - **Getting Started**: Installation and first steps.
109
+ - **Pricing**: Detailed guide on options, strategies, and pricing models.
110
+ - **Backends**: Configuring specific computation backends.
@@ -0,0 +1,65 @@
1
+ # Laakhay Quantlab
2
+
3
+ `laakhay-quantlab` is a high-performance, backend-agnostic quantitative computation layer designed for simulation-heavy research and production analytics. It provides a unified interface over **NumPy**, **JAX**, and **PyTorch**, enabling seamless switching between CPU and GPU backends without code changes.
4
+
5
+ ## Key Features
6
+
7
+ - **Backend Agnostic**: Write once, run on NumPy, JAX, or PyTorch.
8
+ - **Hardware Acceleration**: Transparent GPU/TPU support via JAX/Torch backends.
9
+ - **Vectorized Operations**: Optimized `ArrayBackend` with JIT compilation support.
10
+ - **Simulation Primitives**: Fast Gaussian sampling, Geometric Brownian Motion (GBM), and more.
11
+ - **Options & Pricing (New)**: Comprehensive verification and pricing of derivatives using analytical (Black-Scholes) and numerical (Monte Carlo) methods.
12
+
13
+ ## Ecosystem
14
+
15
+ `laakhay-quantlab` fits into the broader Laakhay quantitative ecosystem:
16
+ 1. **`laakhay-data`**: Market data acquisition and normalization.
17
+ 2. **`laakhay-ta`**: Technical analysis indicators and strategy engine.
18
+ 3. **`laakhay-quantlab`**: Numerical simulation, pricing, and risk modeling.
19
+
20
+ ## Installation
21
+
22
+ ```bash
23
+ pip install laakhay-quantlab
24
+ # extensions: [jax, jax-gpu, torch, all]
25
+ pip install "laakhay-quantlab[all]"
26
+ ```
27
+
28
+ ## Quick Start: Options Pricing
29
+
30
+ The `pricing` module supports a wide range of exotic and vanilla options, along with Greeks calculation.
31
+
32
+ ```python
33
+ from laakhay.quantlab.pricing import (
34
+ EuropeanCall,
35
+ MarketData,
36
+ Pricer,
37
+ PricingMethod
38
+ )
39
+
40
+ # 1. Define Market Conditions
41
+ market = MarketData(spot=100.0, rate=0.05, vol=0.2)
42
+
43
+ # 2. Define Instrument
44
+ option = EuropeanCall(strike=100.0, expiry=1.0)
45
+
46
+ # 3. Price using Black-Scholes (Analytical)
47
+ bs_pricer = Pricer(method=PricingMethod.BLACK_SCHOLES)
48
+ price, greeks = bs_pricer.price_with_greeks(option, market)
49
+
50
+ print(f"Price: {price:.4f}")
51
+ print(f"Delta: {greeks.delta:.4f}")
52
+
53
+ # 4. Price using Monte Carlo (Numerical)
54
+ mc_pricer = Pricer(method=PricingMethod.MONTE_CARLO)
55
+ mc_price = mc_pricer.price(option, market)
56
+
57
+ print(f"MC Price: {mc_price:.4f}")
58
+ ```
59
+
60
+ ## Documentation
61
+
62
+ See the `docs/` directory for detailed guides:
63
+ - **Getting Started**: Installation and first steps.
64
+ - **Pricing**: Detailed guide on options, strategies, and pricing models.
65
+ - **Backends**: Configuring specific computation backends.
@@ -0,0 +1,6 @@
1
+ """
2
+ Quantlab - Quantitative analysis tools for the Laakhay ecosystem
3
+ """
4
+
5
+ __author__ = "Laakhay Corporation"
6
+ __version__ = "0.1.0"
@@ -0,0 +1,81 @@
1
+ """Backend abstraction for array operations."""
2
+
3
+ from . import ops
4
+ from .backend import ArrayBackend, active_backend, backend
5
+ from .interface import AbstractBackend, Backend
6
+ from .registry import (
7
+ convert_array,
8
+ get_backend,
9
+ has_backend,
10
+ infer_backend,
11
+ infer_backend_from_arrays,
12
+ list_backends,
13
+ register,
14
+ set_default,
15
+ )
16
+
17
+
18
+ def _init():
19
+ """Initialize available backends."""
20
+ available = []
21
+
22
+ try:
23
+ from .implementations.numpy import NumpyBackend
24
+
25
+ register("numpy", NumpyBackend())
26
+ available.append("numpy")
27
+ except ImportError:
28
+ pass
29
+
30
+ try:
31
+ from .implementations.jax import JaxBackend
32
+
33
+ register("jax", JaxBackend())
34
+ available.append("jax")
35
+ except ImportError:
36
+ pass
37
+
38
+ try:
39
+ from .implementations.torch import TorchBackend
40
+
41
+ register("torch", TorchBackend())
42
+ available.append("torch")
43
+ except ImportError:
44
+ pass
45
+
46
+ # Always register fallback
47
+ from .implementations.fallback import FallbackBackend
48
+
49
+ register("fallback", FallbackBackend())
50
+
51
+ # Set default to first available real backend, or fallback
52
+ for name in ["numpy", "jax", "torch"]:
53
+ if name in available:
54
+ set_default(name)
55
+ return
56
+
57
+ set_default("fallback")
58
+
59
+
60
+ _init()
61
+
62
+ __all__ = [
63
+ # Core
64
+ "Backend",
65
+ "AbstractBackend",
66
+ "ArrayBackend",
67
+ # High-level API
68
+ "backend",
69
+ "active_backend",
70
+ # Registry
71
+ "register",
72
+ "get_backend",
73
+ "set_default",
74
+ "list_backends",
75
+ "infer_backend",
76
+ "infer_backend_from_arrays",
77
+ "convert_array",
78
+ "has_backend",
79
+ # Ops module
80
+ "ops",
81
+ ]
@@ -0,0 +1,163 @@
1
+ """Backend wrapper with autodiff."""
2
+
3
+ from ..types import Array
4
+ from .registry import get_backend as _get_backend
5
+ from .registry import infer_backend
6
+
7
+
8
+ class ArrayBackend:
9
+ """Backend wrapper with autodiff support."""
10
+
11
+ def __init__(self, backend=None):
12
+ if backend is None:
13
+ self._backend = _get_backend()
14
+ elif isinstance(backend, str):
15
+ self._backend = _get_backend(backend)
16
+ else:
17
+ self._backend = backend
18
+
19
+ @property
20
+ def name(self) -> str:
21
+ return self._backend.name
22
+
23
+ @property
24
+ def supports_autodiff(self) -> bool:
25
+ """Check autodiff support."""
26
+ return self.name in ["jax", "torch"]
27
+
28
+ def __getattr__(self, name):
29
+ return getattr(self._backend, name)
30
+
31
+ @staticmethod
32
+ def from_array(array: Array) -> "ArrayBackend":
33
+ """Create backend from array."""
34
+ backend_name = infer_backend(array)
35
+ if backend_name:
36
+ return ArrayBackend(backend_name)
37
+ return ArrayBackend()
38
+
39
+ def grad(self, func, argnums=0):
40
+ """Compute gradient."""
41
+ if self.name == "jax":
42
+ import jax
43
+
44
+ def scalar_func(*args):
45
+ output = func(*args)
46
+ if hasattr(output, "shape") and output.shape:
47
+ return output.sum()
48
+ return output
49
+
50
+ return jax.grad(scalar_func, argnums=argnums)
51
+ elif self.name == "torch":
52
+
53
+ def torch_grad(*args):
54
+ import torch
55
+
56
+ tensors = []
57
+ for i, arg in enumerate(args):
58
+ if i == argnums:
59
+ t = (
60
+ arg
61
+ if isinstance(arg, torch.Tensor)
62
+ else torch.tensor(arg, dtype=torch.float32)
63
+ )
64
+ t.requires_grad_(True)
65
+ tensors.append(t)
66
+ else:
67
+ t = arg if isinstance(arg, torch.Tensor) else torch.tensor(arg)
68
+ tensors.append(t)
69
+
70
+ output = func(*tensors)
71
+
72
+ if output.numel() > 1:
73
+ output = output.sum()
74
+
75
+ output.backward()
76
+ return tensors[argnums].grad
77
+
78
+ return torch_grad
79
+ else:
80
+ raise RuntimeError(f"Backend {self.name} doesn't support autodiff")
81
+
82
+ def value_and_grad(self, func, argnums=0):
83
+ """Compute value and gradient."""
84
+ if self.name == "jax":
85
+ import jax
86
+
87
+ def wrapped_func(*args):
88
+ output = func(*args)
89
+ scalar = output.sum() if hasattr(output, "shape") and output.shape else output
90
+ return scalar
91
+
92
+ scalar_value_and_grad = jax.value_and_grad(wrapped_func, argnums=argnums)
93
+
94
+ def value_and_grad_wrapper(*args):
95
+ original_output = func(*args)
96
+ _, grad = scalar_value_and_grad(*args)
97
+ return original_output, grad
98
+
99
+ return value_and_grad_wrapper
100
+ elif self.name == "torch":
101
+
102
+ def torch_value_and_grad(*args):
103
+ import torch
104
+
105
+ tensors = []
106
+ for i, arg in enumerate(args):
107
+ if i == argnums:
108
+ t = (
109
+ arg
110
+ if isinstance(arg, torch.Tensor)
111
+ else torch.tensor(arg, dtype=torch.float32)
112
+ )
113
+ t.requires_grad_(True)
114
+ tensors.append(t)
115
+ else:
116
+ t = arg if isinstance(arg, torch.Tensor) else torch.tensor(arg)
117
+ tensors.append(t)
118
+
119
+ output = func(*tensors)
120
+ value = output.detach().clone()
121
+
122
+ if output.numel() > 1:
123
+ output = output.sum()
124
+
125
+ output.backward()
126
+ return value, tensors[argnums].grad
127
+
128
+ return torch_value_and_grad
129
+ else:
130
+ raise RuntimeError(f"Backend {self.name} doesn't support value_and_grad")
131
+
132
+ def vmap(self, func):
133
+ """Vectorize function."""
134
+ if self.name == "jax":
135
+ import jax
136
+
137
+ return jax.vmap(func)
138
+ else:
139
+
140
+ def vmapped(*args):
141
+ results = [func(x, *args[1:]) for x in args[0]]
142
+ return self._backend.stack(results)
143
+
144
+ return vmapped
145
+
146
+ def jit(self, func):
147
+ """JIT compile function."""
148
+ if self.name == "jax":
149
+ import jax
150
+
151
+ return jax.jit(func)
152
+ else:
153
+ return func
154
+
155
+
156
+ def backend(name=None) -> ArrayBackend:
157
+ """Get backend instance."""
158
+ return ArrayBackend(name)
159
+
160
+
161
+ def active_backend() -> ArrayBackend:
162
+ """Get active backend."""
163
+ return ArrayBackend()
@@ -0,0 +1,57 @@
1
+ """Device management."""
2
+
3
+ from __future__ import annotations
4
+
5
+
6
+ class Device:
7
+ """Compute device (CPU/GPU)."""
8
+
9
+ def __init__(self, device_type: str, device_id: int = 0):
10
+ self.type = device_type.lower()
11
+ if self.type == "gpu":
12
+ self.type = "cuda"
13
+ self.id = device_id
14
+
15
+ def __str__(self):
16
+ if self.type == "cpu":
17
+ return "cpu"
18
+ return f"{self.type}:{self.id}"
19
+
20
+ def __eq__(self, other):
21
+ if isinstance(other, str):
22
+ return str(self) == other
23
+ return self.type == other.type and self.id == other.id
24
+
25
+ def __hash__(self):
26
+ return hash((self.type, self.id))
27
+
28
+ def __repr__(self):
29
+ return f"Device({self})"
30
+
31
+ @classmethod
32
+ def cpu(cls):
33
+ """CPU device."""
34
+ return cls("cpu")
35
+
36
+ @classmethod
37
+ def gpu(cls, device_id: int = 0):
38
+ """GPU device."""
39
+ return cls("cuda", device_id)
40
+
41
+
42
+ def get_device(array) -> Device:
43
+ """Infer device from array."""
44
+ if hasattr(array, "device") and callable(array.device):
45
+ device = array.device()
46
+ if hasattr(device, "platform"):
47
+ if device.platform == "gpu":
48
+ return Device.gpu(device.id)
49
+ return Device.cpu()
50
+
51
+ if hasattr(array, "device") and not callable(array.device):
52
+ device = array.device
53
+ if hasattr(device, "type") and device.type == "cuda":
54
+ return Device.gpu(device.index or 0)
55
+ return Device.cpu()
56
+
57
+ return Device.cpu()
@@ -0,0 +1,27 @@
1
+ """Backend implementations."""
2
+
3
+ from .fallback import FallbackBackend
4
+
5
+ __all__ = ["FallbackBackend"]
6
+
7
+ # Import actual backends only if available
8
+ try:
9
+ from .numpy import NumpyBackend # noqa: F401
10
+
11
+ __all__.append("NumpyBackend")
12
+ except ImportError:
13
+ pass
14
+
15
+ try:
16
+ from .jax import JaxBackend # noqa: F401
17
+
18
+ __all__.append("JaxBackend")
19
+ except ImportError:
20
+ pass
21
+
22
+ try:
23
+ from .torch import TorchBackend # noqa: F401
24
+
25
+ __all__.append("TorchBackend")
26
+ except ImportError:
27
+ pass
@@ -0,0 +1,47 @@
1
+ """Fallback backend for when no array libraries are installed."""
2
+
3
+ from ..interface import AbstractBackend
4
+
5
+
6
+ class FallbackBackend(AbstractBackend):
7
+ """Fallback backend that raises helpful errors."""
8
+
9
+ name = "fallback"
10
+
11
+ def __init__(self):
12
+ self._error_msg = (
13
+ "No array backend available. Install one of:\n"
14
+ " pip install numpy\n"
15
+ " pip install jax jaxlib\n"
16
+ " pip install torch"
17
+ )
18
+
19
+ def _not_available(self, *args, **kwargs):
20
+ raise RuntimeError(self._error_msg)
21
+
22
+ def __getattribute__(self, name):
23
+ if name in (
24
+ "name",
25
+ "_error_msg",
26
+ "_not_available",
27
+ "__class__",
28
+ "__init__",
29
+ ):
30
+ return object.__getattribute__(self, name)
31
+ return object.__getattribute__(self, "_not_available")
32
+
33
+ # Add explicit methods to satisfy the protocol
34
+ def gather(self, a, indices, axis=0):
35
+ return self._not_available()
36
+
37
+ def norm(self, a, ord=None, axis=None):
38
+ return self._not_available()
39
+
40
+ def solve(self, a, b):
41
+ return self._not_available()
42
+
43
+ def inv(self, a):
44
+ return self._not_available()
45
+
46
+ def det(self, a):
47
+ return self._not_available()