sigtorch 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.
@@ -0,0 +1,6 @@
1
+ __pycache__/
2
+ *.egg-info/
3
+ .pytest_cache/
4
+ build/
5
+ dist/
6
+ .venv/
sigtorch-0.1.0/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Oschart
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,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.
@@ -0,0 +1,103 @@
1
+ Metadata-Version: 2.5
2
+ Name: sigtorch
3
+ Version: 0.1.0
4
+ Summary: Differentiable signatures and logsignatures in pure PyTorch, with the API of signatory.
5
+ Project-URL: Homepage, https://github.com/Oschart/sigtorch
6
+ Project-URL: Issues, https://github.com/Oschart/sigtorch/issues
7
+ Author: Oschart
8
+ License-Expression: MIT AND Apache-2.0
9
+ License-File: LICENSE
10
+ License-File: LICENSE-signatory
11
+ Keywords: logsignature,path signature,pytorch,rough paths,signatory,signature
12
+ Classifier: Development Status :: 4 - Beta
13
+ Classifier: Intended Audience :: Science/Research
14
+ Classifier: Operating System :: OS Independent
15
+ Classifier: Programming Language :: Python :: 3
16
+ Classifier: Topic :: Scientific/Engineering :: Artificial Intelligence
17
+ Classifier: Topic :: Scientific/Engineering :: Mathematics
18
+ Requires-Python: >=3.9
19
+ Requires-Dist: torch>=1.13
20
+ Provides-Extra: test
21
+ Requires-Dist: iisignature; extra == 'test'
22
+ Requires-Dist: numpy; extra == 'test'
23
+ Requires-Dist: pytest; extra == 'test'
24
+ Description-Content-Type: text/markdown
25
+
26
+ # sigtorch
27
+
28
+ [![tests](https://github.com/Oschart/sigtorch/actions/workflows/tests.yml/badge.svg)](https://github.com/Oschart/sigtorch/actions/workflows/tests.yml)
29
+
30
+ Differentiable path signatures and logsignatures in pure PyTorch, with the API of
31
+ [signatory](https://github.com/patrick-kidger/signatory).
32
+
33
+ signatory is the standard PyTorch library for signatures, but its last release (2021) targets PyTorch 1.9 and
34
+ is a C++ extension that has to be compiled from source on most platforms. sigtorch reimplements its public API in
35
+ plain PyTorch: nothing to compile, any device PyTorch supports, and gradients through autograd.
36
+
37
+ ```python
38
+ import torch
39
+ import sigtorch as signatory # existing signatory code keeps working
40
+
41
+ path = torch.randn(32, 100, 5) # (batch, stream, channels)
42
+ sig = signatory.signature(path, depth=3) # (32, 5 + 5**2 + 5**3)
43
+ logsig = signatory.logsignature(path, depth=3, stream=True)
44
+ ```
45
+
46
+ ## Installation
47
+
48
+ ```bash
49
+ pip install sigtorch
50
+ ```
51
+
52
+ Requires Python 3.9+ and PyTorch 1.13+. The only dependency is `torch`.
53
+
54
+ ## What it covers
55
+
56
+ Everything in signatory 1.2.6's public API, with the same arguments, output layout and conventions:
57
+
58
+ | | |
59
+ |---|---|
60
+ | Signatures | `signature`, `Signature`, `signature_channels`, `extract_signature_term`, `signature_combine`, `multi_signature_combine` |
61
+ | Logsignatures | `logsignature`, `LogSignature`, `signature_to_logsignature`, `SignatureToLogSignature`, `logsignature_channels`, with modes `"words"`, `"brackets"`, `"expand"` |
62
+ | Intervals | `Path` (signatures/logsignatures over any interval, `update`, batch indexing) |
63
+ | Other | `Augment`, `invert_signature`, `lyndon_words`, `lyndon_brackets`, `all_words`, `max_parallelism` (deprecated no-op, as in signatory) |
64
+
65
+ All options are supported: `stream`, `basepoint` (bool or tensor), `inverse`, `initial`, `scalar_term`, at any
66
+ depth. The aliases `Logsignature` and `SignatureToLogsignature` exist too. Not included: `signatory.unstable`, which
67
+ signatory documents as outside its stable API.
68
+
69
+ ## How it is tested
70
+
71
+ - **Against signatory itself.** [tests/make_signatory_fixtures.py](tests/make_signatory_fixtures.py) records the
72
+ outputs *and gradients* of the real signatory 1.2.6 on 536 cases covering every function and every combination of
73
+ options; [tests/test_signatory_parity.py](tests/test_signatory_parity.py) checks sigtorch reproduces all of them
74
+ (float64, relative tolerance 1e-9).
75
+ - **Against [iisignature](https://github.com/bottler/iisignature)**, on longer paths and up to depth 6.
76
+
77
+ ## Differences from signatory
78
+
79
+ The numbers are the same. These behaviours differ:
80
+
81
+ - Gradients come from autograd rather than hand-written backward passes, so second derivatives work.
82
+ - `Path(..., remember_path=False).signature()` works (signatory raises).
83
+ - `Augment(include_time=True)` follows the input's dtype (signatory always builds the time channel in float32, so
84
+ float64 input fails).
85
+ - `invert_signature` returns the signature's dtype and device (signatory always returns float32 on the CPU).
86
+ - `Path.__eq__` compares the stored tensors of both paths.
87
+ - No `signatory.unstable`.
88
+
89
+ ## Implementation notes
90
+
91
+ Depths 1–3 use closed forms (cumulative sums and batched matrix products) that never store a per-step copy of the
92
+ level-2 or level-3 tensors in the non-stream case. Deeper signatures multiply per-segment signatures with Chen's
93
+ identity in a balanced tree (or a parallel prefix scan with `stream=True`), so the number of sequential steps grows
94
+ with the logarithm of the path length.
95
+
96
+ ## Acknowledgements and license
97
+
98
+ sigtorch follows the API and conventions of signatory by Patrick Kidger
99
+ ([Kidger & Lyons, ICLR 2021](https://arxiv.org/abs/2001.00706)). Its numerical core is new code, while `Path`,
100
+ `Augment` and `max_parallelism` are adapted from signatory's Python layer, which is licensed under Apache 2.0
101
+ ([LICENSE-signatory](LICENSE-signatory)). The rest of sigtorch is MIT-licensed ([LICENSE](LICENSE)).
102
+
103
+ If you use sigtorch in research, please also cite signatory.
@@ -0,0 +1,78 @@
1
+ # sigtorch
2
+
3
+ [![tests](https://github.com/Oschart/sigtorch/actions/workflows/tests.yml/badge.svg)](https://github.com/Oschart/sigtorch/actions/workflows/tests.yml)
4
+
5
+ Differentiable path signatures and logsignatures in pure PyTorch, with the API of
6
+ [signatory](https://github.com/patrick-kidger/signatory).
7
+
8
+ signatory is the standard PyTorch library for signatures, but its last release (2021) targets PyTorch 1.9 and
9
+ is a C++ extension that has to be compiled from source on most platforms. sigtorch reimplements its public API in
10
+ plain PyTorch: nothing to compile, any device PyTorch supports, and gradients through autograd.
11
+
12
+ ```python
13
+ import torch
14
+ import sigtorch as signatory # existing signatory code keeps working
15
+
16
+ path = torch.randn(32, 100, 5) # (batch, stream, channels)
17
+ sig = signatory.signature(path, depth=3) # (32, 5 + 5**2 + 5**3)
18
+ logsig = signatory.logsignature(path, depth=3, stream=True)
19
+ ```
20
+
21
+ ## Installation
22
+
23
+ ```bash
24
+ pip install sigtorch
25
+ ```
26
+
27
+ Requires Python 3.9+ and PyTorch 1.13+. The only dependency is `torch`.
28
+
29
+ ## What it covers
30
+
31
+ Everything in signatory 1.2.6's public API, with the same arguments, output layout and conventions:
32
+
33
+ | | |
34
+ |---|---|
35
+ | Signatures | `signature`, `Signature`, `signature_channels`, `extract_signature_term`, `signature_combine`, `multi_signature_combine` |
36
+ | Logsignatures | `logsignature`, `LogSignature`, `signature_to_logsignature`, `SignatureToLogSignature`, `logsignature_channels`, with modes `"words"`, `"brackets"`, `"expand"` |
37
+ | Intervals | `Path` (signatures/logsignatures over any interval, `update`, batch indexing) |
38
+ | Other | `Augment`, `invert_signature`, `lyndon_words`, `lyndon_brackets`, `all_words`, `max_parallelism` (deprecated no-op, as in signatory) |
39
+
40
+ All options are supported: `stream`, `basepoint` (bool or tensor), `inverse`, `initial`, `scalar_term`, at any
41
+ depth. The aliases `Logsignature` and `SignatureToLogsignature` exist too. Not included: `signatory.unstable`, which
42
+ signatory documents as outside its stable API.
43
+
44
+ ## How it is tested
45
+
46
+ - **Against signatory itself.** [tests/make_signatory_fixtures.py](tests/make_signatory_fixtures.py) records the
47
+ outputs *and gradients* of the real signatory 1.2.6 on 536 cases covering every function and every combination of
48
+ options; [tests/test_signatory_parity.py](tests/test_signatory_parity.py) checks sigtorch reproduces all of them
49
+ (float64, relative tolerance 1e-9).
50
+ - **Against [iisignature](https://github.com/bottler/iisignature)**, on longer paths and up to depth 6.
51
+
52
+ ## Differences from signatory
53
+
54
+ The numbers are the same. These behaviours differ:
55
+
56
+ - Gradients come from autograd rather than hand-written backward passes, so second derivatives work.
57
+ - `Path(..., remember_path=False).signature()` works (signatory raises).
58
+ - `Augment(include_time=True)` follows the input's dtype (signatory always builds the time channel in float32, so
59
+ float64 input fails).
60
+ - `invert_signature` returns the signature's dtype and device (signatory always returns float32 on the CPU).
61
+ - `Path.__eq__` compares the stored tensors of both paths.
62
+ - No `signatory.unstable`.
63
+
64
+ ## Implementation notes
65
+
66
+ Depths 1–3 use closed forms (cumulative sums and batched matrix products) that never store a per-step copy of the
67
+ level-2 or level-3 tensors in the non-stream case. Deeper signatures multiply per-segment signatures with Chen's
68
+ identity in a balanced tree (or a parallel prefix scan with `stream=True`), so the number of sequential steps grows
69
+ with the logarithm of the path length.
70
+
71
+ ## Acknowledgements and license
72
+
73
+ sigtorch follows the API and conventions of signatory by Patrick Kidger
74
+ ([Kidger & Lyons, ICLR 2021](https://arxiv.org/abs/2001.00706)). Its numerical core is new code, while `Path`,
75
+ `Augment` and `max_parallelism` are adapted from signatory's Python layer, which is licensed under Apache 2.0
76
+ ([LICENSE-signatory](LICENSE-signatory)). The rest of sigtorch is MIT-licensed ([LICENSE](LICENSE)).
77
+
78
+ If you use sigtorch in research, please also cite signatory.
@@ -0,0 +1,39 @@
1
+ [build-system]
2
+ requires = ["hatchling>=1.27"]
3
+ build-backend = "hatchling.build"
4
+
5
+ [project]
6
+ name = "sigtorch"
7
+ dynamic = ["version"]
8
+ description = "Differentiable signatures and logsignatures in pure PyTorch, with the API of signatory."
9
+ readme = "README.md"
10
+ license = "MIT AND Apache-2.0"
11
+ license-files = ["LICENSE", "LICENSE-signatory"]
12
+ requires-python = ">=3.9"
13
+ authors = [{ name = "Oschart" }]
14
+ keywords = ["signature", "logsignature", "path signature", "rough paths", "pytorch", "signatory"]
15
+ classifiers = [
16
+ "Development Status :: 4 - Beta",
17
+ "Intended Audience :: Science/Research",
18
+ "Operating System :: OS Independent",
19
+ "Programming Language :: Python :: 3",
20
+ "Topic :: Scientific/Engineering :: Artificial Intelligence",
21
+ "Topic :: Scientific/Engineering :: Mathematics",
22
+ ]
23
+ dependencies = ["torch>=1.13"]
24
+
25
+ [project.optional-dependencies]
26
+ test = ["pytest", "numpy", "iisignature"]
27
+
28
+ [project.urls]
29
+ Homepage = "https://github.com/Oschart/sigtorch"
30
+ Issues = "https://github.com/Oschart/sigtorch/issues"
31
+
32
+ [tool.hatch.version]
33
+ path = "src/sigtorch/__init__.py"
34
+
35
+ [tool.hatch.build.targets.sdist]
36
+ include = ["src", "tests", "README.md", "LICENSE", "LICENSE-signatory"]
37
+
38
+ [tool.pytest.ini_options]
39
+ testpaths = ["tests"]
@@ -0,0 +1,23 @@
1
+ """sigtorch: differentiable signatures and logsignatures in pure PyTorch, with the API of signatory.
2
+
3
+ ``import sigtorch as signatory`` is intended to work as a drop-in replacement for code written against signatory 1.2.
4
+ """
5
+
6
+ from .augment import Augment
7
+ from .deprecated import max_parallelism
8
+ from .logsignature_module import (LogSignature, Logsignature, SignatureToLogSignature, SignatureToLogsignature,
9
+ logsignature, logsignature_channels, signature_to_logsignature)
10
+ from .path import Path
11
+ from .signature_inversion_module import invert_signature
12
+ from .signature_module import (Signature, extract_signature_term, multi_signature_combine, signature,
13
+ signature_channels, signature_combine)
14
+ from .utility import all_words, lyndon_brackets, lyndon_words
15
+
16
+ __version__ = "0.1.0"
17
+
18
+ __all__ = [
19
+ "Augment", "LogSignature", "Logsignature", "Path", "Signature", "SignatureToLogSignature",
20
+ "SignatureToLogsignature", "all_words", "extract_signature_term", "invert_signature", "logsignature",
21
+ "logsignature_channels", "lyndon_brackets", "lyndon_words", "max_parallelism", "multi_signature_combine",
22
+ "signature", "signature_channels", "signature_combine", "signature_to_logsignature",
23
+ ]
@@ -0,0 +1,89 @@
1
+ """Signature levels of a piecewise-linear path, given its increments.
2
+
3
+ Depths 1-3 use closed forms built from cumulative sums and batched matrix products, which never materialise the
4
+ per-step level-2/3 tensors of the non-stream signature. Deeper signatures combine per-segment exponentials with Chen's
5
+ identity in a balanced tree (non-stream) or a parallel prefix scan (stream), so the number of sequential steps grows
6
+ with log(length) rather than length.
7
+ """
8
+
9
+ import torch
10
+
11
+ from . import _tensor_algebra as ta
12
+
13
+
14
+ def signature_levels(dX: torch.Tensor, depth: int, stream: bool) -> ta.Levels:
15
+ """Signature levels of the path with increments ``dX`` of shape (B, N, C).
16
+
17
+ Returns levels of shape (B, C**k), or (B, N, C**k) holding the signature of every prefix if ``stream``.
18
+ """
19
+ if depth <= 3:
20
+ return _closed_form_stream(dX, depth) if stream else _closed_form(dX, depth)
21
+ return _scan(dX, depth) if stream else _tree(dX, depth)
22
+
23
+
24
+ def _exclusive_cumsum(x: torch.Tensor) -> torch.Tensor:
25
+ """Cumulative sum over dim 1 of everything strictly before each step."""
26
+ return x.cumsum(dim=1) - x
27
+
28
+
29
+ def _closed_form(dX: torch.Tensor, depth: int) -> ta.Levels:
30
+ batch, _, channels = dX.shape
31
+ levels = [dX.sum(dim=1)]
32
+ if depth >= 2:
33
+ before = _exclusive_cumsum(dX) # S1 up to the start of each segment
34
+ # sum_t S1_before[t] (x) dX[t] + sum_t dX[t] (x) dX[t] / 2
35
+ S2 = torch.bmm(before.transpose(1, 2), dX) + 0.5 * torch.bmm(dX.transpose(1, 2), dX)
36
+ levels.append(S2.reshape(batch, channels ** 2))
37
+ if depth >= 3:
38
+ outer = torch.einsum('bti,btj->btij', dX, dX)
39
+ S2_before = _exclusive_cumsum(torch.einsum('bti,btj->btij', before, dX) + 0.5 * outer)
40
+ # Chen: S3 += S2_before (x) dX + S1_before (x) dX^2 / 2 + dX^3 / 6, summed over segments
41
+ S3 = (torch.einsum('btij,btk->bijk', S2_before, dX)
42
+ + 0.5 * torch.einsum('bti,btjk->bijk', before, outer)
43
+ + torch.einsum('bti,btjk->bijk', dX, outer) / 6)
44
+ levels.append(S3.reshape(batch, channels ** 3))
45
+ return levels
46
+
47
+
48
+ def _closed_form_stream(dX: torch.Tensor, depth: int) -> ta.Levels:
49
+ batch, length, channels = dX.shape
50
+ S1 = dX.cumsum(dim=1)
51
+ levels = [S1]
52
+ if depth >= 2:
53
+ before = S1 - dX
54
+ outer = torch.einsum('bti,btj->btij', dX, dX)
55
+ S2 = (torch.einsum('bti,btj->btij', before, dX) + 0.5 * outer).cumsum(dim=1)
56
+ levels.append(S2.reshape(batch, length, channels ** 2))
57
+ if depth >= 3:
58
+ S2_before = torch.cat([torch.zeros_like(S2[:, :1]), S2[:, :-1]], dim=1)
59
+ S3 = (torch.einsum('btij,btk->btijk', S2_before, dX)
60
+ + 0.5 * torch.einsum('bti,btjk->btijk', before, outer)
61
+ + torch.einsum('bti,btjk->btijk', dX, outer) / 6).cumsum(dim=1)
62
+ levels.append(S3.reshape(batch, length, channels ** 3))
63
+ return levels
64
+
65
+
66
+ def _tree(dX: torch.Tensor, depth: int) -> ta.Levels:
67
+ """Multiplies the segment exponentials pairwise, halving their number each round."""
68
+ levels = ta.restricted_exp(dX, depth)
69
+ while levels[0].size(1) > 1:
70
+ tail = None
71
+ if levels[0].size(1) % 2: # an odd one out joins the next round at the end
72
+ tail = [x[:, -1:] for x in levels]
73
+ levels = [x[:, :-1] for x in levels]
74
+ levels = ta.mult([x[:, 0::2] for x in levels], [x[:, 1::2] for x in levels])
75
+ if tail is not None:
76
+ levels = [torch.cat([x, t], dim=1) for x, t in zip(levels, tail)]
77
+ return [x[:, 0] for x in levels]
78
+
79
+
80
+ def _scan(dX: torch.Tensor, depth: int) -> ta.Levels:
81
+ """Inclusive prefix products of the segment exponentials (Hillis-Steele scan)."""
82
+ levels = ta.restricted_exp(dX, depth)
83
+ length = levels[0].size(1)
84
+ offset = 1
85
+ while offset < length:
86
+ combined = ta.mult([x[:, :-offset] for x in levels], [x[:, offset:] for x in levels])
87
+ levels = [torch.cat([x[:, :offset], c], dim=1) for x, c in zip(levels, combined)]
88
+ offset *= 2
89
+ return levels
@@ -0,0 +1,75 @@
1
+ """Operations on elements of the truncated tensor algebra.
2
+
3
+ An element is a list ``[x_1, ..., x_depth]`` where ``x_k`` has shape ``(..., C**k)``: the level-k tensor flattened in
4
+ row-major order, after any number of leading batch dimensions. The scalar term is implicit: 1 for signatures (group
5
+ elements), 0 for log-signatures (Lie elements). All operations broadcast over the leading dimensions.
6
+ """
7
+
8
+ from typing import List, Optional
9
+
10
+ import torch
11
+
12
+ Levels = List[torch.Tensor]
13
+
14
+
15
+ def split_levels(flat: torch.Tensor, channels: int, depth: int) -> Levels:
16
+ """Splits a ``(..., C + C**2 + ... + C**depth)`` tensor into its levels."""
17
+ return list(torch.split(flat, [channels ** k for k in range(1, depth + 1)], dim=-1))
18
+
19
+
20
+ def _outer(a: torch.Tensor, b: torch.Tensor) -> torch.Tensor:
21
+ """(..., m) x (..., n) -> (..., m * n), the flattened tensor product."""
22
+ return (a.unsqueeze(-1) * b.unsqueeze(-2)).flatten(-2)
23
+
24
+
25
+ def restricted_exp(x: torch.Tensor, depth: int) -> Levels:
26
+ """exp(x) for a level-1 element ``x`` of shape (..., C): the signature of a single straight segment."""
27
+ levels = [x]
28
+ for k in range(2, depth + 1):
29
+ levels.append(_outer(levels[-1], x) / k)
30
+ return levels
31
+
32
+
33
+ def _product(a: List[Optional[torch.Tensor]], b: List[Optional[torch.Tensor]]) -> List[Optional[torch.Tensor]]:
34
+ """Truncated product of two elements with zero scalar term. ``None`` marks a level known to be zero."""
35
+ depth = len(a)
36
+ out: List[Optional[torch.Tensor]] = [None] * depth
37
+ for k in range(1, depth): # output level k + 1
38
+ for i in range(k): # a at level i + 1, b at level k - i
39
+ if a[i] is not None and b[k - 1 - i] is not None:
40
+ term = _outer(a[i], b[k - 1 - i])
41
+ out[k] = term if out[k] is None else out[k] + term
42
+ return out
43
+
44
+
45
+ def mult(a: Levels, b: Levels) -> Levels:
46
+ """(1 + a) * (1 + b) - 1: the product of two group elements, e.g. Chen's identity for signatures."""
47
+ cross = _product(a, b)
48
+ return [x + y if c is None else x + y + c for x, y, c in zip(a, b, cross)]
49
+
50
+
51
+ def log(a: Levels) -> Levels:
52
+ """log(1 + a) = a - a^2 / 2 + a^3 / 3 - ..., truncated."""
53
+ result = list(a)
54
+ power: List[Optional[torch.Tensor]] = list(a)
55
+ for n in range(2, len(a) + 1):
56
+ power = _product(power, a)
57
+ coeff = (-1) ** (n + 1) / n
58
+ result = [r if p is None else r + coeff * p for r, p in zip(result, power)]
59
+ return result
60
+
61
+
62
+ def inverse(a: Levels) -> Levels:
63
+ """Inverse of a group-like element such as a signature: reverse every word and multiply level k by (-1)^k.
64
+
65
+ This equals the signature of the time-reversed path.
66
+ """
67
+ channels = a[0].size(-1)
68
+ out = []
69
+ for k, x in enumerate(a, start=1):
70
+ batch_shape = x.shape[:-1]
71
+ nb = len(batch_shape)
72
+ x = x.reshape(*batch_shape, *([channels] * k))
73
+ x = x.permute(*range(nb), *range(nb + k - 1, nb - 1, -1)).reshape(*batch_shape, channels ** k)
74
+ out.append(x if k % 2 == 0 else -x)
75
+ return out