|
1 | | -# Adding New Frameworks to arraybridge |
| 1 | +# Adding a framework |
2 | 2 |
|
3 | | -With the metaclass-registry integration, adding a new framework is now simpler and requires no manual wiring. |
| 3 | +This is a maintainer how-to for extending ArrayBridge's closed framework |
| 4 | +taxonomy. Applications should consume `MemoryType`; they should not add their |
| 5 | +own framework registry. |
4 | 6 |
|
5 | | -## Quick Overview |
| 7 | +## 1. Define typed leaves |
6 | 8 |
|
7 | | -To add a new framework (e.g., MXNet), you need to: |
| 9 | +Add an `ArrayOperations` bundle in |
| 10 | +`src/arraybridge/array_operations.py`. It must provide four ordinary callables: |
8 | 11 |
|
9 | | -1. Add the new memory type to the `MemoryType` enum in `types.py` |
10 | | -2. Add framework configuration to `_FRAMEWORK_CONFIG` in `framework_config.py` |
11 | | -3. The converter automatically registers itself - no manual registration needed! |
| 12 | +- project an array to NumPy; |
| 13 | +- create an array from NumPy on the requested framework-local device; |
| 14 | +- stack prepared 2D arrays into one 3D array; |
| 15 | +- apply the framework's dtype-scaling semantics. |
12 | 16 |
|
13 | | -## Step-by-Step Guide |
| 17 | +Define device, stream, DLPack, cleanup, and OOM leaves in |
| 18 | +`src/arraybridge/types.py`. Use the no-op defaults in `FrameworkRuntime` only |
| 19 | +when the framework genuinely lacks that capability. Do not encode behavior as |
| 20 | +strings or add a parallel `MemoryType`-keyed table. |
14 | 21 |
|
15 | | -### Step 1: Add to MemoryType Enum |
| 22 | +## 2. Add the declaration |
16 | 23 |
|
17 | | -Edit `src/arraybridge/types.py`: |
| 24 | +Add one `MemoryType` member carrying: |
18 | 25 |
|
19 | | -```python |
20 | | -class MemoryType(Enum): |
21 | | - """Enum representing different array/tensor framework types.""" |
22 | | - |
23 | | - NUMPY = "numpy" |
24 | | - CUPY = "cupy" |
25 | | - TORCH = "torch" |
26 | | - TENSORFLOW = "tensorflow" |
27 | | - JAX = "jax" |
28 | | - PYCLESPERANTO = "pyclesperanto" |
29 | | - MXNET = "mxnet" # <-- Add your new framework |
30 | | -``` |
31 | | - |
32 | | -### Step 2: Add Framework Configuration |
33 | | - |
34 | | -Edit `src/arraybridge/framework_config.py` and add a new entry to `_FRAMEWORK_CONFIG`: |
35 | | - |
36 | | -```python |
37 | | -_FRAMEWORK_CONFIG = { |
38 | | - # ... existing configurations ... |
39 | | - |
40 | | - MemoryType.MXNET: { |
41 | | - # Metadata |
42 | | - 'import_name': 'mxnet', |
43 | | - 'display_name': 'MXNet', |
44 | | - 'is_gpu': True, |
45 | | - |
46 | | - # Conversion operations - these define the converter methods |
47 | | - 'conversion_ops': { |
48 | | - 'to_numpy': 'data.asnumpy()', # How to convert to numpy |
49 | | - 'from_numpy': '{mod}.nd.array(data, ctx={mod}.gpu(gpu_id))', # How to create from numpy |
50 | | - 'from_dlpack': '{mod}.nd.from_dlpack(data)', # DLPack support (if available) |
51 | | - 'move_to_device': 'data.as_in_context({mod}.gpu(device_id))', # Move between devices |
52 | | - }, |
53 | | - |
54 | | - # Device operations (optional) |
55 | | - 'get_device_id': 'data.context.device_id', |
56 | | - 'set_device': None, |
57 | | - |
58 | | - # Other configuration... |
59 | | - 'supports_dlpack': True, |
60 | | - 'validate_dlpack': None, |
61 | | - |
62 | | - # ... add other required fields based on existing frameworks |
63 | | - } |
64 | | -} |
65 | | -``` |
| 26 | +1. its stable value and import name; |
| 27 | +2. its display name and module aliases; |
| 28 | +3. whether it is GPU-backed; |
| 29 | +4. any environment defaults that must be set before first import; |
| 30 | +5. its `FrameworkRuntime` leaves; |
| 31 | +6. its `ArrayOperations` bundle. |
66 | 32 |
|
67 | | -### Step 3: That's It! |
| 33 | +The converter classes, target conversion methods, compatibility operation view, |
| 34 | +dtype-scaling view, cleanup adapters, and framework decorator are generated |
| 35 | +from the enum. Do not wire them manually. |
68 | 36 |
|
69 | | -The converter class is automatically created and registered when the module loads. You can verify it works: |
| 37 | +## 3. Prove the extension |
70 | 38 |
|
71 | | -```python |
72 | | -from arraybridge.converters_registry import ConverterBase, get_converter |
73 | | -from arraybridge.types import MemoryType |
| 39 | +Add focused tests for: |
74 | 40 |
|
75 | | -# Check that it's registered |
76 | | -print(sorted(ConverterBase.__registry__.keys())) |
77 | | -# Output: ['cupy', 'jax', 'mxnet', 'numpy', 'pyclesperanto', 'tensorflow', 'torch'] |
| 41 | +- module-name detection and optional-dependency failure; |
| 42 | +- NumPy round trips and every supported DLPack pair; |
| 43 | +- CPU-only installations of a nominally GPU framework; |
| 44 | +- invalid, negative, and multiple framework-local device IDs; |
| 45 | +- same-framework moves between two devices; |
| 46 | +- one-, two-, and multi-slice stack/unstack behavior; |
| 47 | +- immutable array types; |
| 48 | +- cleanup and OOM behavior without importing an absent framework; |
| 49 | +- generated registry and export completeness. |
78 | 50 |
|
79 | | -# Get the converter |
80 | | -mxnet_converter = get_converter("mxnet") |
81 | | -print(mxnet_converter.memory_type) # Output: 'mxnet' |
| 51 | +Run: |
82 | 52 |
|
83 | | -# Use via MemoryType enum |
84 | | -converter = MemoryType.MXNET.converter |
| 53 | +```bash |
| 54 | +ruff check src tests |
| 55 | +black --check src tests |
| 56 | +mypy src --ignore-missing-imports |
| 57 | +pytest |
| 58 | +python -m sphinx -E -W --keep-going -b html docs/source /tmp/arraybridge-docs |
85 | 59 | ``` |
86 | 60 |
|
87 | | -## What Happens Behind the Scenes |
88 | | - |
89 | | -1. **Auto-generation**: A `MxnetConverter` class is created dynamically with methods from `conversion_ops` |
90 | | -2. **Auto-registration**: The metaclass `AutoRegisterMeta` automatically registers it in `ConverterBase.__registry__` |
91 | | -3. **Auto-validation**: Module load validates that all `MemoryType` values have registered converters |
92 | | -4. **Auto-methods**: The converter automatically gets `to_X()` methods for all other frameworks |
93 | | - |
94 | | -## Benefits of This Approach |
95 | | - |
96 | | -### Before (Manual Wiring - Old System) |
97 | | -```python |
98 | | -# Had to manually create converter class with all methods |
99 | | -class MxnetConverter(MemoryTypeConverter): |
100 | | - def to_numpy(self, data, gpu_id): |
101 | | - return data.asnumpy() |
102 | | - |
103 | | - def from_numpy(self, data, gpu_id): |
104 | | - return mxnet.nd.array(data) |
105 | | - |
106 | | - def to_torch(self, data, gpu_id): |
107 | | - raise NotImplementedError |
108 | | - |
109 | | - def to_cupy(self, data, gpu_id): |
110 | | - raise NotImplementedError |
111 | | - |
112 | | -# Had to manually register |
113 | | -_CONVERTERS[MemoryType.MXNET] = MxnetConverter() |
114 | | -``` |
115 | | - |
116 | | -### After (Auto-registration - New System) |
117 | | -```python |
118 | | -# Add one enum member and one config entry; everything else is automatic. |
119 | | -class MemoryType(Enum): |
120 | | - # Existing members omitted. |
121 | | - MXNET = "mxnet" |
122 | | - |
123 | | -_FRAMEWORK_CONFIG[MemoryType.MXNET] = { |
124 | | - 'conversion_ops': { |
125 | | - 'to_numpy': 'data.asnumpy()', |
126 | | - # ... |
127 | | - } |
128 | | -} |
129 | | -``` |
130 | | - |
131 | | -## Framework Configuration Reference |
132 | | - |
133 | | -Required fields in `conversion_ops`: |
134 | | -- `to_numpy`: Expression to convert framework data to numpy |
135 | | -- `from_numpy`: Expression to create framework data from numpy |
136 | | -- `from_dlpack`: Expression for DLPack conversion (or `None`) |
137 | | -- `move_to_device`: Expression to move data between devices |
138 | | - |
139 | | -Available template variables in expressions: |
140 | | -- `{mod}`: The imported module (e.g., `mxnet`) |
141 | | -- `data`: The input data |
142 | | -- `gpu_id` / `device_id`: Target device ID |
143 | | - |
144 | | -## Testing Your New Framework |
145 | | - |
146 | | -Add tests in `tests/test_converters.py`: |
147 | | - |
148 | | -```python |
149 | | -@pytest.mark.mxnet |
150 | | -def test_convert_numpy_to_mxnet(self, mxnet_available): |
151 | | - """Test converting NumPy to MXNet.""" |
152 | | - if not mxnet_available: |
153 | | - pytest.skip("MXNet not available") |
154 | | - |
155 | | - import mxnet as mx |
156 | | - arr = np.array([1.0, 2.0, 3.0], dtype=np.float32) |
157 | | - result = convert_memory(arr, source_type="numpy", target_type="mxnet", gpu_id=0) |
158 | | - |
159 | | - assert isinstance(result, mx.nd.NDArray) |
160 | | - np.testing.assert_array_almost_equal(result.asnumpy(), arr) |
161 | | -``` |
162 | | - |
163 | | -## Common Patterns |
164 | | - |
165 | | -### GPU Framework with DLPack |
166 | | -```python |
167 | | -conversion_ops = { |
168 | | - 'to_numpy': 'data.cpu().numpy()', |
169 | | - 'from_numpy': '{mod}.from_numpy(data).to(device=gpu_id)', |
170 | | - 'from_dlpack': '{mod}.from_dlpack(data)', |
171 | | - 'move_to_device': 'data.to(device=device_id)', |
172 | | -} |
173 | | -``` |
174 | | - |
175 | | -### CPU-only Framework |
176 | | -```python |
177 | | -conversion_ops = { |
178 | | - 'to_numpy': 'np.array(data)', |
179 | | - 'from_numpy': '{mod}.array(data)', |
180 | | - 'from_dlpack': None, # Not supported |
181 | | - 'move_to_device': 'data', # No-op for CPU |
182 | | -} |
183 | | -``` |
184 | | - |
185 | | -### Complex Operations with Helpers |
186 | | -If you need complex logic, define a helper function in `framework_config.py`: |
187 | | - |
188 | | -```python |
189 | | -def _mxnet_special_conversion(data, gpu_id, mod): |
190 | | - # Complex logic here |
191 | | - return result |
192 | | - |
193 | | -_FRAMEWORK_CONFIG[MemoryType.MXNET] = { |
194 | | - 'conversion_ops': { |
195 | | - 'from_numpy': _mxnet_special_conversion, # Use callable instead of string |
196 | | - # ... |
197 | | - } |
198 | | -} |
199 | | -``` |
200 | | - |
201 | | -## Troubleshooting |
202 | | - |
203 | | -### Converter not registered |
204 | | -Make sure: |
205 | | -1. You added the framework to `MemoryType` enum |
206 | | -2. You added configuration to `_FRAMEWORK_CONFIG` |
207 | | -3. The key in `_FRAMEWORK_CONFIG` matches the `MemoryType` enum value |
208 | | - |
209 | | -### Import errors |
210 | | -If you get import errors, check: |
211 | | -1. The `import_name` matches the actual package name |
212 | | -2. The `conversion_ops` expressions use correct module syntax |
213 | | - |
214 | | -### Validation errors |
215 | | -Run this to check registration: |
216 | | -```python |
217 | | -from arraybridge.converters_registry import _validate_registry |
218 | | -_validate_registry() # Raises RuntimeError if validation fails |
219 | | -``` |
| 61 | +When GPU hardware is available, also exercise every installed framework pair in |
| 62 | +one process. This catches import-order, allocator-coexistence, DLPack, and real |
| 63 | +API-shape defects that isolated mocks cannot prove. |
0 commit comments