Skip to content

Commit ebc9fd9

Browse files
committed
Make framework behavior declaration-owned
1 parent 9c4d1cb commit ebc9fd9

43 files changed

Lines changed: 2963 additions & 3239 deletions

Some content is hidden

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

‎.github/badges/coverage.svg‎

Lines changed: 0 additions & 1 deletion
This file was deleted.

‎.github/workflows/coverage-pages.yml‎

Lines changed: 4 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -6,7 +6,7 @@ on:
66
workflow_dispatch:
77

88
permissions:
9-
contents: write # Needed for badge commit
9+
contents: read
1010
pages: write
1111
id-token: write
1212

@@ -40,7 +40,6 @@ jobs:
4040
pip install torch --index-url https://download.pytorch.org/whl/cpu
4141
4242
- name: Run tests with coverage
43-
continue-on-error: true # Continue workflow even if tests fail
4443
run: |
4544
mkdir -p site
4645
python -m pytest --cov=arraybridge \
@@ -50,8 +49,7 @@ jobs:
5049
5150
- name: Generate coverage badge
5251
run: |
53-
mkdir -p .github/badges
54-
genbadge coverage -i coverage.xml -o .github/badges/coverage.svg -n "coverage"
52+
genbadge coverage -i coverage.xml -o site/coverage-badge.svg -n "coverage"
5553
5654
- name: Create index.html and README
5755
run: |
@@ -72,7 +70,7 @@ jobs:
7270
# Create README.md in the site directory
7371
echo "# arraybridge Code Coverage Reports" > site/README.md
7472
echo "" >> site/README.md
75-
echo "This site contains the code coverage reports for the [arraybridge](https://github.com/trissim/arraybridge) project." >> site/README.md
73+
echo "This site contains the code coverage reports for the [arraybridge](https://github.com/OpenHCSDev/arraybridge) project." >> site/README.md
7674
echo "" >> site/README.md
7775
echo "## Navigation" >> site/README.md
7876
echo "" >> site/README.md
@@ -85,19 +83,10 @@ jobs:
8583
echo "" >> site/README.md
8684
echo "Last updated: $(date)" >> site/README.md
8785
88-
- name: Commit and push if coverage badge changed
89-
if: github.event_name == 'push' && github.ref == 'refs/heads/main'
90-
run: |
91-
git config --local user.email "github-actions[bot]@users.noreply.github.com"
92-
git config --local user.name "github-actions[bot]"
93-
git add .github/badges/coverage.svg -f
94-
git commit -m "chore: update coverage badge" || exit 0
95-
git push
96-
9786
- name: Check GitHub Pages status
9887
run: |
9988
echo "⚠️ IMPORTANT: Make sure GitHub Pages is enabled in your repository settings!"
100-
echo "Go to https://github.com/trissim/arraybridge/settings/pages"
89+
echo "Go to https://github.com/OpenHCSDev/arraybridge/settings/pages"
10190
echo "Set 'Source' to 'GitHub Actions' to enable GitHub Pages deployment."
10291
10392
- name: Setup Pages

‎.github/workflows/publish.yml‎

Lines changed: 20 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -20,6 +20,8 @@ jobs:
2020
steps:
2121
- name: Checkout code
2222
uses: actions/checkout@v4
23+
with:
24+
fetch-depth: 0
2325

2426
- name: Set up Python
2527
uses: actions/setup-python@v5
@@ -29,7 +31,21 @@ jobs:
2931
- name: Install build dependencies
3032
run: |
3133
python -m pip install --upgrade pip
32-
pip install build
34+
pip install -e ".[dev]"
35+
36+
- name: Validate source and tests
37+
run: |
38+
ruff check src/ scripts/
39+
black --check src/ scripts/
40+
mypy src/ --ignore-missing-imports
41+
pytest -q --no-cov
42+
43+
- name: Verify release tag and main ancestry
44+
run: |
45+
declared_version=$(python -c 'import tomllib; print(tomllib.load(open("pyproject.toml", "rb"))["project"]["version"])')
46+
test "$GITHUB_REF_NAME" = "v$declared_version"
47+
git fetch origin main
48+
git merge-base --is-ancestor "$GITHUB_SHA" origin/main
3349
3450
- name: Build package
3551
run: python -m build
@@ -39,13 +55,13 @@ jobs:
3955
pip install twine
4056
twine check dist/*
4157
58+
- name: Publish to PyPI
59+
uses: pypa/gh-action-pypi-publish@release/v1
60+
4261
- name: Create GitHub Release
4362
uses: softprops/action-gh-release@v2
4463
with:
4564
files: dist/*
4665
generate_release_notes: true
4766
env:
4867
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
49-
50-
- name: Publish to PyPI
51-
uses: pypa/gh-action-pypi-publish@release/v1

‎ADDING_NEW_FRAMEWORKS.md‎

Lines changed: 47 additions & 203 deletions
Original file line numberDiff line numberDiff line change
@@ -1,219 +1,63 @@
1-
# Adding New Frameworks to arraybridge
1+
# Adding a framework
22

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

5-
## Quick Overview
7+
## 1. Define typed leaves
68

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:
811

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

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

15-
### Step 1: Add to MemoryType Enum
22+
## 2. Add the declaration
1623

17-
Edit `src/arraybridge/types.py`:
24+
Add one `MemoryType` member carrying:
1825

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

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

69-
The converter class is automatically created and registered when the module loads. You can verify it works:
37+
## 3. Prove the extension
7038

71-
```python
72-
from arraybridge.converters_registry import ConverterBase, get_converter
73-
from arraybridge.types import MemoryType
39+
Add focused tests for:
7440

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

79-
# Get the converter
80-
mxnet_converter = get_converter("mxnet")
81-
print(mxnet_converter.memory_type) # Output: 'mxnet'
51+
Run:
8252

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
8559
```
8660

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

Comments
 (0)