copyengine 0.1.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.
Files changed (68) hide show
  1. copyengine-0.1.0/.github/workflows/ci.yml +135 -0
  2. copyengine-0.1.0/.gitignore +7 -0
  3. copyengine-0.1.0/AGENTS.md +75 -0
  4. copyengine-0.1.0/CHANGELOG.md +35 -0
  5. copyengine-0.1.0/CLAUDE.md +1 -0
  6. copyengine-0.1.0/CMakeLists.txt +203 -0
  7. copyengine-0.1.0/LICENSE +201 -0
  8. copyengine-0.1.0/PKG-INFO +206 -0
  9. copyengine-0.1.0/README.md +182 -0
  10. copyengine-0.1.0/bench/bench_serving.py +683 -0
  11. copyengine-0.1.0/bench/bench_torch.py +258 -0
  12. copyengine-0.1.0/cmake/embed.cmake +10 -0
  13. copyengine-0.1.0/docker/Dockerfile +21 -0
  14. copyengine-0.1.0/docker/build-wheels.sh +98 -0
  15. copyengine-0.1.0/include/copyengine/copyengine.h +111 -0
  16. copyengine-0.1.0/include/copyengine/copyengine.hpp +16 -0
  17. copyengine-0.1.0/include/copyengine/engine.hpp +132 -0
  18. copyengine-0.1.0/include/copyengine/error.hpp +27 -0
  19. copyengine-0.1.0/include/copyengine/frontend.hpp +42 -0
  20. copyengine-0.1.0/include/copyengine/ir.hpp +149 -0
  21. copyengine-0.1.0/include/copyengine/probe.hpp +21 -0
  22. copyengine-0.1.0/include/copyengine/types.hpp +83 -0
  23. copyengine-0.1.0/justfile +25 -0
  24. copyengine-0.1.0/pyproject.toml +50 -0
  25. copyengine-0.1.0/python/copyengine/__init__.py +51 -0
  26. copyengine-0.1.0/python/copyengine/_api.py +450 -0
  27. copyengine-0.1.0/python/copyengine/_mode.py +118 -0
  28. copyengine-0.1.0/python/copyengine/_shim.py +136 -0
  29. copyengine-0.1.0/python/copyengine/_shim_key.py +37 -0
  30. copyengine-0.1.0/python/copyengine/_tensor.py +220 -0
  31. copyengine-0.1.0/python/copyengine/_torch_ops.py +62 -0
  32. copyengine-0.1.0/src/backends/cuda/driver.cpp +105 -0
  33. copyengine-0.1.0/src/backends/cuda/driver.hpp +80 -0
  34. copyengine-0.1.0/src/backends/cuda/executor.cpp +1195 -0
  35. copyengine-0.1.0/src/backends/cuda/executor.hpp +12 -0
  36. copyengine-0.1.0/src/backends/cuda/kernels.cu +330 -0
  37. copyengine-0.1.0/src/backends/cuda/probe.cpp +404 -0
  38. copyengine-0.1.0/src/backends/cuda/probe.hpp +14 -0
  39. copyengine-0.1.0/src/backends/executor.hpp +38 -0
  40. copyengine-0.1.0/src/backends/host/host.cpp +231 -0
  41. copyengine-0.1.0/src/backends/host/host.hpp +54 -0
  42. copyengine-0.1.0/src/capi/capi.cpp +154 -0
  43. copyengine-0.1.0/src/core/config.hpp.in +6 -0
  44. copyengine-0.1.0/src/core/convert.hpp +271 -0
  45. copyengine-0.1.0/src/core/engine.cpp +876 -0
  46. copyengine-0.1.0/src/core/frontend.cpp +84 -0
  47. copyengine-0.1.0/src/core/ir.cpp +554 -0
  48. copyengine-0.1.0/src/core/json.hpp +269 -0
  49. copyengine-0.1.0/src/core/plan.cpp +248 -0
  50. copyengine-0.1.0/src/core/plan.hpp +143 -0
  51. copyengine-0.1.0/src/core/probe.cpp +60 -0
  52. copyengine-0.1.0/src/core/tuner.cpp +366 -0
  53. copyengine-0.1.0/src/core/tuner.hpp +121 -0
  54. copyengine-0.1.0/src/core/types.cpp +30 -0
  55. copyengine-0.1.0/src/core/version.cpp +11 -0
  56. copyengine-0.1.0/src/python/module.cpp +352 -0
  57. copyengine-0.1.0/src/torch/ops.cpp +145 -0
  58. copyengine-0.1.0/src/torch/shim.cpp +271 -0
  59. copyengine-0.1.0/tests/cpp/test_capi.c +58 -0
  60. copyengine-0.1.0/tests/cpp/test_convert.cpp +63 -0
  61. copyengine-0.1.0/tests/cpp/test_probe.cpp +28 -0
  62. copyengine-0.1.0/tests/cpp/test_smoke.cpp +23 -0
  63. copyengine-0.1.0/tests/python/test_cuda.py +541 -0
  64. copyengine-0.1.0/tests/python/test_engine.py +703 -0
  65. copyengine-0.1.0/tests/python/test_ir.py +203 -0
  66. copyengine-0.1.0/tests/python/test_probe.py +17 -0
  67. copyengine-0.1.0/tests/python/test_scope.py +203 -0
  68. copyengine-0.1.0/tests/python/test_smoke.py +8 -0
@@ -0,0 +1,135 @@
1
+ name: CI
2
+
3
+ on:
4
+ push:
5
+ pull_request:
6
+ workflow_dispatch:
7
+
8
+ permissions:
9
+ contents: read
10
+
11
+ env:
12
+ TORCH_CPU_INDEX: https://download.pytorch.org/whl/cpu
13
+
14
+ jobs:
15
+ # Core, C ABI and the numpy path: no torch.
16
+ core:
17
+ runs-on: ubuntu-24.04
18
+ timeout-minutes: 20
19
+ strategy:
20
+ fail-fast: false
21
+ matrix:
22
+ python: ["3.10", "3.12", "3.13"]
23
+ steps:
24
+ - uses: actions/checkout@v6
25
+ - uses: actions/setup-python@v6
26
+ with:
27
+ python-version: ${{ matrix.python }}
28
+ - uses: taiki-e/install-action@just
29
+ - run: sudo apt-get update && sudo apt-get install -y ninja-build
30
+ - run: pip install scikit-build-core nanobind pytest
31
+ - run: just test
32
+
33
+ # Per torch release: the stable-ABI ops and the interception shim built for
34
+ # it, the whole suite with the shim and again with the Python mode (the same
35
+ # semantics must hold), and the shim exported for the release wheel.
36
+ torch:
37
+ runs-on: ubuntu-24.04
38
+ timeout-minutes: 30
39
+ strategy:
40
+ fail-fast: false
41
+ matrix:
42
+ torch: ["2.9.1", "2.10.0", "2.11.0"]
43
+ steps:
44
+ - uses: actions/checkout@v6
45
+ - uses: actions/setup-python@v6
46
+ with:
47
+ python-version: "3.12"
48
+ - uses: taiki-e/install-action@just
49
+ - run: sudo apt-get update && sudo apt-get install -y ninja-build
50
+ - run: pip install scikit-build-core nanobind pytest numpy
51
+ - run: pip install "torch==${{ matrix.torch }}" --index-url "$TORCH_CPU_INDEX"
52
+ - run: just test
53
+ - name: Same suite, Python interception mode
54
+ run: CE_SHIM=0 pytest -q
55
+ - name: Check both torch layers loaded
56
+ working-directory: /tmp
57
+ # The stable-ABI ops need torch >= 2.10; older torch uses the Python path for explicit copies.
58
+ run: python -c "import torch, copyengine as ce; v = tuple(map(int, torch.__version__.split('+')[0].split('.')[:2])); assert (ce._torch_ops.copy_ is not None) == (v >= (2, 10)), ce._torch_ops.error; assert ce._shim.lib is not None, ce._shim.error"
59
+
60
+ # The stable ABI claim and the compile-on-import path: built with the newest
61
+ # torch, run with the oldest supported one.
62
+ cross-torch:
63
+ runs-on: ubuntu-24.04
64
+ timeout-minutes: 30
65
+ steps:
66
+ - uses: actions/checkout@v6
67
+ - uses: actions/setup-python@v6
68
+ with:
69
+ python-version: "3.12"
70
+ - run: sudo apt-get update && sudo apt-get install -y ninja-build
71
+ - run: pip install scikit-build-core nanobind pytest numpy
72
+ - run: pip install "torch==2.11.0" --index-url "$TORCH_CPU_INDEX"
73
+ - run: pip wheel --no-build-isolation --no-deps . -w dist
74
+ - run: pip install "torch==2.9.1" --index-url "$TORCH_CPU_INDEX"
75
+ - run: pip install --no-deps dist/*.whl
76
+ - name: On torch older than the ops' stable ABI, the ops stay off and the shim still loads
77
+ working-directory: /tmp
78
+ run: python -c "import copyengine as ce; assert ce._torch_ops.copy_ is None; assert ce._shim.lib is not None, ce._shim.error; print(ce._torch_ops.error); print(ce._shim.lib._name)"
79
+ - run: pytest -q
80
+
81
+ # Release wheels and sdist (docker/build-wheels.sh, which also runs locally):
82
+ # manylinux_2_28, CUDA kernels for every architecture, a prebuilt shim per
83
+ # supported torch release. On a v* tag the version must match CMakeLists.txt
84
+ # and the files are attached to the GitHub release.
85
+ wheel:
86
+ if: startsWith(github.ref, 'refs/tags/v') || github.event_name == 'workflow_dispatch'
87
+ needs: [core, torch, cross-torch]
88
+ runs-on: ubuntu-24.04
89
+ timeout-minutes: 120
90
+ container: quay.io/pypa/manylinux_2_28_x86_64
91
+ steps:
92
+ - uses: actions/checkout@v6
93
+ - name: Tag matches the version
94
+ if: startsWith(github.ref, 'refs/tags/v')
95
+ run: |
96
+ want=$(sed -n 's/^project(copyengine VERSION \([0-9.]*\).*/\1/p' CMakeLists.txt)
97
+ test "${GITHUB_REF_NAME#v}" = "$want" || { echo "tag $GITHUB_REF_NAME, CMakeLists.txt $want"; exit 1; }
98
+ - run: docker/build-wheels.sh
99
+ - uses: actions/upload-artifact@v5
100
+ with:
101
+ name: dist
102
+ path: dist/*
103
+
104
+ release:
105
+ if: startsWith(github.ref, 'refs/tags/v')
106
+ needs: [wheel]
107
+ runs-on: ubuntu-24.04
108
+ permissions:
109
+ contents: write
110
+ steps:
111
+ - uses: actions/download-artifact@v5
112
+ with:
113
+ name: dist
114
+ path: dist
115
+ - env:
116
+ GH_TOKEN: ${{ github.token }}
117
+ run: gh release create "$GITHUB_REF_NAME" dist/* --repo "$GITHUB_REPOSITORY" --verify-tag --generate-notes
118
+
119
+ # PyPI trusted publishing (OIDC): the pypi.org project trusts this workflow
120
+ # and the `pypi` environment; no token is stored.
121
+ pypi:
122
+ if: startsWith(github.ref, 'refs/tags/v')
123
+ needs: [wheel]
124
+ runs-on: ubuntu-24.04
125
+ environment:
126
+ name: pypi
127
+ url: https://pypi.org/project/copyengine/
128
+ permissions:
129
+ id-token: write
130
+ steps:
131
+ - uses: actions/download-artifact@v5
132
+ with:
133
+ name: dist
134
+ path: dist
135
+ - uses: pypa/gh-action-pypi-publish@release/v1
@@ -0,0 +1,7 @@
1
+ /build/
2
+ /dist/
3
+ *.egg-info/
4
+ __pycache__/
5
+ *.pyc
6
+ .venv/
7
+ compile_commands.json
@@ -0,0 +1,75 @@
1
+ # copyengine engineering rules
2
+
3
+ ## Layout
4
+
5
+ - `include/copyengine/copyengine.h` is the stable C ABI (`ce_` prefix). Any
6
+ incompatible change bumps `CE_ABI_VERSION`. Until the first release, the C
7
+ ABI, Python API and profile format may change freely; from then on they
8
+ follow semver.
9
+ - `include/copyengine/*.hpp` + `src/core`: the platform-independent planner
10
+ (namespace `ce`): IR and lowering (`ir`), planning and dependencies (`plan`),
11
+ tuner, engine, probe. It must not include torch or CUDA headers.
12
+ - `src/backends/host`: host executor and the conversion table.
13
+ - `src/backends/cuda`: driver loader (dlopen + `cuGetProcAddress` at the
14
+ header's `CUDA_VERSION`), probe, executor, and `kernels.cu` (AOT fatbin,
15
+ embedded by `cmake/embed.cmake`).
16
+ - `src/core/convert.hpp` is shared verbatim by host code and CUDA kernels;
17
+ host and device conversions must stay bit-identical (no FMA: host files use
18
+ `-ffp-contract=off`, kernels `--fmad=false`).
19
+ - `src/capi` implements the C ABI; `src/python` is the nanobind extension
20
+ `copyengine._core`; `python/copyengine` is the Python layer.
21
+ - torch integration is layered, and all logic stays in the torch-free core,
22
+ reached through the `FrontendApi` table that `_core` exports:
23
+ `src/torch/ops.cpp` on the stable libtorch ABI (descriptors, explicit APIs as
24
+ custom ops; one build for every torch >= 2.10), and `src/torch/shim.cpp`, the
25
+ scope interception, holding only dispatch-key registration and redispatch.
26
+ The shim uses the DeferredInit key, refuses to load if something else holds
27
+ it, and is admitted only after a verified copy; it is prebuilt for the
28
+ build-time torch and otherwise compiled on import, cached per torch build.
29
+ Its fallback is `python/copyengine/_mode.py` (TorchDispatchMode) with
30
+ identical semantics: behavior may differ only in speed, never in results,
31
+ and `tests/python/test_scope.py` runs under both.
32
+ - The version lives only in `project(... VERSION ...)` in `CMakeLists.txt`.
33
+
34
+ ## Invariants
35
+
36
+ - Ops carry absolute element indices (address / itemsize); pure copies are
37
+ normalized to bytes. Dependencies and merging rely on this.
38
+ - Every Executor strategy must be correct for any group it is offered.
39
+ `passthrough` (each op as submitted) is always correct, but it is measured
40
+ only when its call count is bounded: it is never a multi-second baseline.
41
+ - New platform features are admitted only after a verified test copy.
42
+ - Backend tables built per group go in `Group::exec_cache`; hot paths do not
43
+ re-plan.
44
+ - No regression: the framework's own copy is the baseline. Dominance-safe
45
+ transforms apply directly; a speculative strategy is used only after it wins
46
+ a paired A/B against the baseline that counts host and GPU time. Ties keep
47
+ the baseline. Where no native copy exists there is no original to protect:
48
+ candidates are explored alike and the fastest locks.
49
+ - Measuring must not stall a run: hopeless candidates are dropped after one
50
+ sample, and online re-checks only run finalists within 2x of the locked one.
51
+ - A group touches several allocations; no copy call, 2-D block or staged
52
+ interval may cross an allocation boundary (the driver rejects it).
53
+ - The native baseline is offered only for dtype pairs whose bits match ce's,
54
+ backed by a test.
55
+ - Hot paths never synchronize; only warmup exploration and validation may.
56
+ - Intercepted `copy_` keeps the caller's `non_blocking` semantics; explicit
57
+ `ce.copy_` returns with host-side copies complete.
58
+
59
+ ## Scope
60
+
61
+ - Commit code only: no design notes, benchmark results, or machine-specific
62
+ data (hostnames, paths, GPU models, driver versions).
63
+ - copyengine is a library; do not add a CLI.
64
+
65
+ ## Verification
66
+
67
+ - `just test` builds the C++ library, runs ctest, installs the Python package
68
+ and runs pytest (CUDA tests skip without a GPU).
69
+ - GPU work runs inside `just docker-shell`.
70
+ - `python bench/bench_torch.py` compares against torch on a GPU.
71
+
72
+ ## Commits
73
+
74
+ - Emoji conventional commits on `master`, for example `✨ feat: add Runs IR`.
75
+ Rebase, no merge commits.
@@ -0,0 +1,35 @@
1
+ # Changelog
2
+
3
+ copyengine follows [semantic versioning](https://semver.org). From 0.1.0 on,
4
+ the Python API, the C ABI (`CE_ABI_VERSION`) and the tuning profile format
5
+ change incompatibly only in a new minor (0.x) or major release.
6
+
7
+ ## 0.1.0
8
+
9
+ First release.
10
+
11
+ - `ce.scope()`: inside it, unchanged torch `copy_` calls are queued, merged
12
+ and issued together; every other op is ordered after the queued copies it
13
+ touches. A C++ dispatcher shim does the interception (prebuilt for torch
14
+ 2.9, 2.10 and 2.11, compiled on import for others); a pure-Python
15
+ interception with the same results is the fallback.
16
+ - Explicit API: `ce.copy_` for any strided views with broadcast,
17
+ `ce.lazy(...)` views torch cannot express (gather + permute + slice),
18
+ `ce.gather` / `ce.scatter_`, `ce.segments`, conversions and quantization
19
+ with `ce.Elementwise`, `Engine.freeze()` replay.
20
+ - Strategies on CUDA: merged and batched DMA (`cuMemcpyBatchAsync`), 2-D
21
+ copies, vectorized copy and conversion kernels, dense link copies with the
22
+ reordering done on the GPU, pinned bounce buffers for pageable memory. Host
23
+ copies run on worker threads.
24
+ - Measured choices: torch's own copy is the baseline; other strategies must
25
+ win a paired A/B, and locked decisions are re-checked online.
26
+ - dtypes: float64/32/16, bfloat16, int64/32/16/8, uint8, bool. Host and GPU
27
+ conversions are bit-identical.
28
+ - Platforms: Linux x86_64, Python 3.10+, CUDA 12.x and 13.x drivers (loaded at
29
+ runtime), torch 2.9+ for `scope()` interception, 2.10+ for the explicit API
30
+ as torch custom ops (older torch runs it from Python). A stable C ABI and CMake
31
+ package for C and C++ callers.
32
+
33
+ Known limits: no fp8 dtypes; copies between two GPUs are implemented but have
34
+ not been tested on a multi-GPU machine; small explicit copies pay a few
35
+ microseconds of host overhead more than torch.
@@ -0,0 +1 @@
1
+ @./AGENTS.md
@@ -0,0 +1,203 @@
1
+ cmake_minimum_required(VERSION 3.26)
2
+ project(copyengine VERSION 0.1.0 LANGUAGES C CXX)
3
+
4
+ set(CMAKE_CXX_STANDARD 20)
5
+ set(CMAKE_CXX_STANDARD_REQUIRED ON)
6
+ set(CMAKE_CXX_EXTENSIONS OFF)
7
+ set(CMAKE_POSITION_INDEPENDENT_CODE ON)
8
+ set(CMAKE_EXPORT_COMPILE_COMMANDS ON)
9
+
10
+ set(CE_CUDA "AUTO" CACHE STRING "Build the CUDA backend: ON, OFF or AUTO (if the toolkit headers are found)")
11
+ option(CE_BUILD_TESTS "Build C++ tests" ${PROJECT_IS_TOP_LEVEL})
12
+ # scikit-build-core sets SKBUILD=2, which option() would read as OFF.
13
+ if(DEFINED SKBUILD)
14
+ set(_ce_python_default ON)
15
+ else()
16
+ set(_ce_python_default OFF)
17
+ endif()
18
+ option(CE_BUILD_PYTHON "Build the Python extension" ${_ce_python_default})
19
+
20
+ configure_file(src/core/config.hpp.in ${CMAKE_CURRENT_BINARY_DIR}/generated/copyengine/config.hpp @ONLY)
21
+
22
+ # Planner core, host backend and C ABI. Platform backends are added below.
23
+ add_library(copyengine
24
+ src/core/version.cpp
25
+ src/core/probe.cpp
26
+ src/core/ir.cpp
27
+ src/core/types.cpp
28
+ src/core/plan.cpp
29
+ src/core/tuner.cpp
30
+ src/core/engine.cpp
31
+ src/core/frontend.cpp
32
+ src/backends/host/host.cpp
33
+ src/capi/capi.cpp
34
+ )
35
+ add_library(copyengine::copyengine ALIAS copyengine)
36
+ # Host and device conversions must agree bit for bit: no FMA contraction.
37
+ set_source_files_properties(src/backends/host/host.cpp PROPERTIES COMPILE_OPTIONS "-ffp-contract=off")
38
+ find_package(Threads REQUIRED)
39
+ target_link_libraries(copyengine PRIVATE Threads::Threads)
40
+ target_include_directories(copyengine
41
+ PUBLIC
42
+ $<BUILD_INTERFACE:${CMAKE_CURRENT_SOURCE_DIR}/include>
43
+ $<BUILD_INTERFACE:${CMAKE_CURRENT_BINARY_DIR}/generated>
44
+ PRIVATE src
45
+ )
46
+ target_compile_options(copyengine PRIVATE
47
+ $<$<CXX_COMPILER_ID:GNU,Clang>:-Wall -Wextra -Wpedantic -Werror=return-type>
48
+ # GCC 13 false positive on std::variant holding std::shared_ptr (core/json.hpp)
49
+ $<$<CXX_COMPILER_ID:GNU>:-Wno-maybe-uninitialized>
50
+ )
51
+ set_target_properties(copyengine PROPERTIES C_VISIBILITY_PRESET hidden CXX_VISIBILITY_PRESET hidden)
52
+ target_compile_definitions(copyengine PRIVATE CE_BUILDING_LIBRARY)
53
+
54
+ # CUDA backend: needs only the toolkit headers. The driver is dlopen'ed at
55
+ # runtime, so nothing links against libcuda or cudart.
56
+ set(CE_WITH_CUDA OFF)
57
+ if(NOT CE_CUDA STREQUAL "OFF")
58
+ find_package(CUDAToolkit QUIET)
59
+ if(CUDAToolkit_FOUND)
60
+ set(CE_WITH_CUDA ON)
61
+ elseif(CE_CUDA STREQUAL "ON")
62
+ message(FATAL_ERROR "CE_CUDA=ON but the CUDA toolkit was not found")
63
+ endif()
64
+ endif()
65
+ set(CE_CUDA_KERNELS OFF)
66
+ if(CE_WITH_CUDA)
67
+ target_sources(copyengine PRIVATE src/backends/cuda/driver.cpp src/backends/cuda/probe.cpp
68
+ src/backends/cuda/executor.cpp)
69
+ target_include_directories(copyengine SYSTEM PRIVATE ${CUDAToolkit_INCLUDE_DIRS})
70
+ target_link_libraries(copyengine PRIVATE ${CMAKE_DL_LIBS})
71
+
72
+ # Copy kernels: compiled AOT to a fatbin with nvcc and embedded as a byte
73
+ # array; loaded at runtime with cuModuleLoadData (no cudart dependency).
74
+ set(CE_CUDA_ARCHS "75;80;86;89;90;100;120" CACHE STRING
75
+ "SM architectures for the kernel fatbin (PTX of the last one is added), or 'native'")
76
+ find_program(CE_NVCC nvcc HINTS ${CUDAToolkit_BIN_DIR})
77
+ if(CE_NVCC)
78
+ set(CE_CUDA_KERNELS ON)
79
+ if(CE_CUDA_ARCHS STREQUAL "native")
80
+ set(_gencode -arch=native)
81
+ else()
82
+ set(_gencode)
83
+ foreach(a IN LISTS CE_CUDA_ARCHS)
84
+ list(APPEND _gencode -gencode arch=compute_${a},code=sm_${a})
85
+ set(_last ${a})
86
+ endforeach()
87
+ list(APPEND _gencode -gencode arch=compute_${_last},code=compute_${_last})
88
+ endif()
89
+ set(_fatbin ${CMAKE_CURRENT_BINARY_DIR}/ce_kernels.fatbin)
90
+ set(_embed ${CMAKE_CURRENT_BINARY_DIR}/ce_kernels_fatbin.c)
91
+ add_custom_command(
92
+ OUTPUT ${_fatbin}
93
+ # compress-mode=size: ~27x smaller; needs a CUDA 12.4+ era driver to load,
94
+ # older drivers fail kernel admission with a clear reason.
95
+ COMMAND ${CE_NVCC} --fatbin -std=c++17 -O3 --fmad=false --compress-mode=size ${_gencode}
96
+ -I${CMAKE_CURRENT_SOURCE_DIR}/src -o ${_fatbin} ${CMAKE_CURRENT_SOURCE_DIR}/src/backends/cuda/kernels.cu
97
+ DEPENDS src/backends/cuda/kernels.cu src/core/convert.hpp
98
+ COMMENT "Compiling copy kernels (${CE_CUDA_ARCHS})"
99
+ VERBATIM)
100
+ add_custom_command(
101
+ OUTPUT ${_embed}
102
+ COMMAND ${CMAKE_COMMAND} -DINPUT=${_fatbin} -DOUTPUT=${_embed} -DNAME=ce_kernels_fatbin
103
+ -P ${CMAKE_CURRENT_SOURCE_DIR}/cmake/embed.cmake
104
+ DEPENDS ${_fatbin} cmake/embed.cmake
105
+ VERBATIM)
106
+ target_sources(copyengine PRIVATE ${_embed})
107
+ else()
108
+ message(WARNING "nvcc not found: CUDA conversions and kernel strategies will be unavailable")
109
+ endif()
110
+ endif()
111
+ target_compile_definitions(copyengine PRIVATE CE_CUDA_KERNELS=$<BOOL:${CE_CUDA_KERNELS}>)
112
+ target_compile_definitions(copyengine PRIVATE CE_WITH_CUDA=$<BOOL:${CE_WITH_CUDA}>)
113
+ message(STATUS "copyengine: CUDA backend ${CE_WITH_CUDA}, kernels ${CE_CUDA_KERNELS}")
114
+
115
+ if(CE_BUILD_TESTS)
116
+ enable_testing()
117
+ add_executable(ce_test_smoke tests/cpp/test_smoke.cpp)
118
+ target_link_libraries(ce_test_smoke PRIVATE copyengine::copyengine)
119
+ add_test(NAME smoke COMMAND ce_test_smoke)
120
+ add_executable(ce_test_probe tests/cpp/test_probe.cpp)
121
+ target_link_libraries(ce_test_probe PRIVATE copyengine::copyengine)
122
+ add_test(NAME probe COMMAND ce_test_probe)
123
+ add_executable(ce_test_capi tests/cpp/test_capi.c)
124
+ target_link_libraries(ce_test_capi PRIVATE copyengine::copyengine)
125
+ add_test(NAME capi COMMAND ce_test_capi)
126
+ add_executable(ce_test_convert tests/cpp/test_convert.cpp)
127
+ target_link_libraries(ce_test_convert PRIVATE copyengine::copyengine)
128
+ target_include_directories(ce_test_convert PRIVATE src)
129
+ target_compile_options(ce_test_convert PRIVATE -ffp-contract=off)
130
+ add_test(NAME convert COMMAND ce_test_convert)
131
+ endif()
132
+
133
+ if(CE_BUILD_PYTHON)
134
+ find_package(Python 3.10 REQUIRED
135
+ COMPONENTS Interpreter Development.Module ${SKBUILD_SABI_COMPONENT})
136
+ execute_process(
137
+ COMMAND "${Python_EXECUTABLE}" -m nanobind --cmake_dir
138
+ OUTPUT_STRIP_TRAILING_WHITESPACE OUTPUT_VARIABLE nanobind_ROOT)
139
+ find_package(nanobind CONFIG REQUIRED)
140
+ nanobind_add_module(_core STABLE_ABI NB_STATIC src/python/module.cpp)
141
+ target_link_libraries(_core PRIVATE copyengine)
142
+ install(TARGETS _core LIBRARY DESTINATION copyengine)
143
+
144
+ # Interception shim sources, laid out as in the wheel: the runtime compiles
145
+ # them for any torch the prebuilt shim below does not match.
146
+ set(_shim_src ${CMAKE_CURRENT_BINARY_DIR}/_shim_src)
147
+ configure_file(src/torch/shim.cpp ${_shim_src}/shim.cpp COPYONLY)
148
+ foreach(h frontend engine ir types)
149
+ configure_file(include/copyengine/${h}.hpp ${_shim_src}/include/copyengine/${h}.hpp COPYONLY)
150
+ endforeach()
151
+ install(DIRECTORY ${_shim_src} DESTINATION copyengine)
152
+
153
+ # copyengine._torch_stable: explicit APIs as torch custom ops on the stable
154
+ # libtorch ABI (torch >= 2.10), one binary for every later torch. Optional:
155
+ # without it the Python layer issues copies itself.
156
+ set(CE_TORCH "AUTO" CACHE STRING "Build the stable-ABI torch extension: ON, OFF or AUTO (if torch >= 2.10 imports)")
157
+ if(NOT CE_TORCH STREQUAL "OFF")
158
+ string(CONCAT _q "import torch; from torch.utils import cpp_extension as c; "
159
+ "v = tuple(int(x) for x in torch.__version__.split('+')[0].split('.')[:2]); "
160
+ "assert v >= (2, 10), torch.__version__; ")
161
+ execute_process(COMMAND "${Python_EXECUTABLE}" -c "${_q}print(';'.join(c.include_paths()), end='')"
162
+ RESULT_VARIABLE _torch_rc OUTPUT_VARIABLE _torch_inc ERROR_VARIABLE _torch_err)
163
+ execute_process(COMMAND "${Python_EXECUTABLE}" -c "${_q}print(';'.join(c.library_paths()), end='')"
164
+ OUTPUT_VARIABLE _torch_lib ERROR_QUIET)
165
+ if(_torch_rc EQUAL 0)
166
+ find_library(CE_TORCH_CPU torch_cpu PATHS ${_torch_lib} NO_DEFAULT_PATH)
167
+ find_library(CE_TORCH_C10 c10 PATHS ${_torch_lib} NO_DEFAULT_PATH)
168
+ add_library(copyengine_torch MODULE src/torch/ops.cpp)
169
+ target_include_directories(copyengine_torch SYSTEM PRIVATE ${_torch_inc})
170
+ target_include_directories(copyengine_torch PRIVATE $<TARGET_PROPERTY:copyengine,INTERFACE_INCLUDE_DIRECTORIES>)
171
+ # Only the stable ABI as of torch 2.10 may be used.
172
+ target_compile_definitions(copyengine_torch PRIVATE TORCH_TARGET_VERSION=0x020A000000000000)
173
+ target_link_libraries(copyengine_torch PRIVATE ${CE_TORCH_CPU} ${CE_TORCH_C10} ${CMAKE_DL_LIBS})
174
+ set_target_properties(copyengine_torch PROPERTIES PREFIX "" OUTPUT_NAME "_torch_stable"
175
+ CXX_VISIBILITY_PRESET hidden)
176
+ install(TARGETS copyengine_torch LIBRARY DESTINATION copyengine)
177
+ message(STATUS "copyengine: stable-ABI torch extension ON")
178
+
179
+ # The interception shim, prebuilt for the build-time torch, under the key
180
+ # the runtime looks up (python/copyengine/_shim_key.py). CI adds shims
181
+ # for other torch releases next to it.
182
+ execute_process(COMMAND "${Python_EXECUTABLE}" -c "import torch; print(int(torch._C._GLIBCXX_USE_CXX11_ABI), end='')"
183
+ OUTPUT_VARIABLE _torch_abi)
184
+ execute_process(COMMAND "${Python_EXECUTABLE}" ${CMAKE_CURRENT_SOURCE_DIR}/python/copyengine/_shim_key.py
185
+ ${_shim_src} ${PROJECT_VERSION}
186
+ OUTPUT_VARIABLE _shim_key RESULT_VARIABLE _shim_key_rc)
187
+ find_library(CE_TORCH_LIB torch PATHS ${_torch_lib} NO_DEFAULT_PATH)
188
+ if(_shim_key_rc EQUAL 0)
189
+ add_library(copyengine_shim MODULE ${_shim_src}/shim.cpp)
190
+ target_include_directories(copyengine_shim SYSTEM PRIVATE ${_torch_inc})
191
+ target_include_directories(copyengine_shim PRIVATE ${_shim_src}/include)
192
+ target_compile_definitions(copyengine_shim PRIVATE _GLIBCXX_USE_CXX11_ABI=${_torch_abi})
193
+ target_link_libraries(copyengine_shim PRIVATE ${CE_TORCH_C10} ${CE_TORCH_CPU} ${CE_TORCH_LIB} ${CMAKE_DL_LIBS})
194
+ set_target_properties(copyengine_shim PROPERTIES PREFIX "" OUTPUT_NAME "libcopyengine_shim" CXX_VISIBILITY_PRESET hidden)
195
+ install(TARGETS copyengine_shim LIBRARY DESTINATION copyengine/shims/${_shim_key})
196
+ endif()
197
+ elseif(CE_TORCH STREQUAL "ON")
198
+ message(FATAL_ERROR "CE_TORCH=ON but torch >= 2.10 is not importable: ${_torch_err}")
199
+ else()
200
+ message(STATUS "copyengine: stable-ABI torch extension OFF (torch >= 2.10 not importable at build time)")
201
+ endif()
202
+ endif()
203
+ endif()
@@ -0,0 +1,201 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright [yyyy] [name of copyright owner]
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.