padic-ml 0.0.1__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
padic_ml-0.0.1/LICENSE ADDED
@@ -0,0 +1,202 @@
1
+
2
+ Apache License
3
+ Version 2.0, January 2004
4
+ http://www.apache.org/licenses/
5
+
6
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
7
+
8
+ 1. Definitions.
9
+
10
+ "License" shall mean the terms and conditions for use, reproduction,
11
+ and distribution as defined by Sections 1 through 9 of this document.
12
+
13
+ "Licensor" shall mean the copyright owner or entity authorized by
14
+ the copyright owner that is granting the License.
15
+
16
+ "Legal Entity" shall mean the union of the acting entity and all
17
+ other entities that control, are controlled by, or are under common
18
+ control with that entity. For the purposes of this definition,
19
+ "control" means (i) the power, direct or indirect, to cause the
20
+ direction or management of such entity, whether by contract or
21
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
22
+ outstanding shares, or (iii) beneficial ownership of such entity.
23
+
24
+ "You" (or "Your") shall mean an individual or Legal Entity
25
+ exercising permissions granted by this License.
26
+
27
+ "Source" form shall mean the preferred form for making modifications,
28
+ including but not limited to software source code, documentation
29
+ source, and configuration files.
30
+
31
+ "Object" form shall mean any form resulting from mechanical
32
+ transformation or translation of a Source form, including but
33
+ not limited to compiled object code, generated documentation,
34
+ and conversions to other media types.
35
+
36
+ "Work" shall mean the work of authorship, whether in Source or
37
+ Object form, made available under the License, as indicated by a
38
+ copyright notice that is included in or attached to the work
39
+ (an example is provided in the Appendix below).
40
+
41
+ "Derivative Works" shall mean any work, whether in Source or Object
42
+ form, that is based on (or derived from) the Work and for which the
43
+ editorial revisions, annotations, elaborations, or other modifications
44
+ represent, as a whole, an original work of authorship. For the purposes
45
+ of this License, Derivative Works shall not include works that remain
46
+ separable from, or merely link (or bind by name) to the interfaces of,
47
+ the Work and Derivative Works thereof.
48
+
49
+ "Contribution" shall mean any work of authorship, including
50
+ the original version of the Work and any modifications or additions
51
+ to that Work or Derivative Works thereof, that is intentionally
52
+ submitted to Licensor for inclusion in the Work by the copyright owner
53
+ or by an individual or Legal Entity authorized to submit on behalf of
54
+ the copyright owner. For the purposes of this definition, "submitted"
55
+ means any form of electronic, verbal, or written communication sent
56
+ to the Licensor or its representatives, including but not limited to
57
+ communication on electronic mailing lists, source code control systems,
58
+ and issue tracking systems that are managed by, or on behalf of, the
59
+ Licensor for the purpose of discussing and improving the Work, but
60
+ excluding communication that is conspicuously marked or otherwise
61
+ designated in writing by the copyright owner as "Not a Contribution."
62
+
63
+ "Contributor" shall mean Licensor and any individual or Legal Entity
64
+ on behalf of whom a Contribution has been received by Licensor and
65
+ subsequently incorporated within the Work.
66
+
67
+ 2. Grant of Copyright License. Subject to the terms and conditions of
68
+ this License, each Contributor hereby grants to You a perpetual,
69
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
70
+ copyright license to reproduce, prepare Derivative Works of,
71
+ publicly display, publicly perform, sublicense, and distribute the
72
+ Work and such Derivative Works in Source or Object form.
73
+
74
+ 3. Grant of Patent License. Subject to the terms and conditions of
75
+ this License, each Contributor hereby grants to You a perpetual,
76
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
77
+ (except as stated in this section) patent license to make, have made,
78
+ use, offer to sell, sell, import, and otherwise transfer the Work,
79
+ where such license applies only to those patent claims licensable
80
+ by such Contributor that are necessarily infringed by their
81
+ Contribution(s) alone or by combination of their Contribution(s)
82
+ with the Work to which such Contribution(s) was submitted. If You
83
+ institute patent litigation against any entity (including a
84
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
85
+ or a Contribution incorporated within the Work constitutes direct
86
+ or contributory patent infringement, then any patent licenses
87
+ granted to You under this License for that Work shall terminate
88
+ as of the date such litigation is filed.
89
+
90
+ 4. Redistribution. You may reproduce and distribute copies of the
91
+ Work or Derivative Works thereof in any medium, with or without
92
+ modifications, and in Source or Object form, provided that You
93
+ meet the following conditions:
94
+
95
+ (a) You must give any other recipients of the Work or
96
+ Derivative Works a copy of this License; and
97
+
98
+ (b) You must cause any modified files to carry prominent notices
99
+ stating that You changed the files; and
100
+
101
+ (c) You must retain, in the Source form of any Derivative Works
102
+ that You distribute, all copyright, patent, trademark, and
103
+ attribution notices from the Source form of the Work,
104
+ excluding those notices that do not pertain to any part of
105
+ the Derivative Works; and
106
+
107
+ (d) If the Work includes a "NOTICE" text file as part of its
108
+ distribution, then any Derivative Works that You distribute must
109
+ include a readable copy of the attribution notices contained
110
+ within such NOTICE file, excluding those notices that do not
111
+ pertain to any part of the Derivative Works, in at least one
112
+ of the following places: within a NOTICE text file distributed
113
+ as part of the Derivative Works; within the Source form or
114
+ documentation, if provided along with the Derivative Works; or,
115
+ within a display generated by the Derivative Works, if and
116
+ wherever such third-party notices normally appear. The contents
117
+ of the NOTICE file are for informational purposes only and
118
+ do not modify the License. You may add Your own attribution
119
+ notices within Derivative Works that You distribute, alongside
120
+ or as an addendum to the NOTICE text from the Work, provided
121
+ that such additional attribution notices cannot be construed
122
+ as modifying the License.
123
+
124
+ You may add Your own copyright statement to Your modifications and
125
+ may provide additional or different license terms and conditions
126
+ for use, reproduction, or distribution of Your modifications, or
127
+ for any such Derivative Works as a whole, provided Your use,
128
+ reproduction, and distribution of the Work otherwise complies with
129
+ the conditions stated in this License.
130
+
131
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
132
+ any Contribution intentionally submitted for inclusion in the Work
133
+ by You to the Licensor shall be under the terms and conditions of
134
+ this License, without any additional terms or conditions.
135
+ Notwithstanding the above, nothing herein shall supersede or modify
136
+ the terms of any separate license agreement you may have executed
137
+ with Licensor regarding such Contributions.
138
+
139
+ 6. Trademarks. This License does not grant permission to use the trade
140
+ names, trademarks, service marks, or product names of the Licensor,
141
+ except as required for reasonable and customary use in describing the
142
+ origin of the Work and reproducing the content of the NOTICE file.
143
+
144
+ 7. Disclaimer of Warranty. Unless required by applicable law or
145
+ agreed to in writing, Licensor provides the Work (and each
146
+ Contributor provides its Contributions) on an "AS IS" BASIS,
147
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
148
+ implied, including, without limitation, any warranties or conditions
149
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
150
+ PARTICULAR PURPOSE. You are solely responsible for determining the
151
+ appropriateness of using or redistributing the Work and assume any
152
+ risks associated with Your exercise of permissions under this License.
153
+
154
+ 8. Limitation of Liability. In no event and under no legal theory,
155
+ whether in tort (including negligence), contract, or otherwise,
156
+ unless required by applicable law (such as deliberate and grossly
157
+ negligent acts) or agreed to in writing, shall any Contributor be
158
+ liable to You for damages, including any direct, indirect, special,
159
+ incidental, or consequential damages of any character arising as a
160
+ result of this License or out of the use or inability to use the
161
+ Work (including but not limited to damages for loss of goodwill,
162
+ work stoppage, computer failure or malfunction, or any and all
163
+ other commercial damages or losses), even if such Contributor
164
+ has been advised of the possibility of such damages.
165
+
166
+ 9. Accepting Warranty or Additional Liability. While redistributing
167
+ the Work or Derivative Works thereof, You may choose to offer,
168
+ and charge a fee for, acceptance of support, warranty, indemnity,
169
+ or other liability obligations and/or rights consistent with this
170
+ License. However, in accepting such obligations, You may act only
171
+ on Your own behalf and on Your sole responsibility, not on behalf
172
+ of any other Contributor, and only if You agree to indemnify,
173
+ defend, and hold each Contributor harmless for any liability
174
+ incurred by, or claims asserted against, such Contributor by reason
175
+ of your accepting any such warranty or additional liability.
176
+
177
+ END OF TERMS AND CONDITIONS
178
+
179
+ APPENDIX: How to apply the Apache License to your work.
180
+
181
+ To apply the Apache License to your work, attach the following
182
+ boilerplate notice, with the fields enclosed by brackets "[]"
183
+ replaced with your own identifying information. (Don't include
184
+ the brackets!) The text should be enclosed in the appropriate
185
+ comment syntax for the file format. We also recommend that a
186
+ file or class name and description of purpose be included on the
187
+ same "printed page" as the copyright notice for easier
188
+ identification within third-party archives.
189
+
190
+ Copyright [yyyy] [name of copyright owner]
191
+
192
+ Licensed under the Apache License, Version 2.0 (the "License");
193
+ you may not use this file except in compliance with the License.
194
+ You may obtain a copy of the License at
195
+
196
+ http://www.apache.org/licenses/LICENSE-2.0
197
+
198
+ Unless required by applicable law or agreed to in writing, software
199
+ distributed under the License is distributed on an "AS IS" BASIS,
200
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
201
+ See the License for the specific language governing permissions and
202
+ limitations under the License.
@@ -0,0 +1,51 @@
1
+ Metadata-Version: 2.4
2
+ Name: padic-ml
3
+ Version: 0.0.1
4
+ Summary: JAX library for differentiable training of p-adic neural networks
5
+ Author: Padic ML Authors
6
+ License-Expression: Apache-2.0
7
+ Project-URL: Homepage, https://github.com/google-deepmind/padic-ml
8
+ Project-URL: Repository, https://github.com/google-deepmind/padic-ml
9
+ Keywords: jax,p-adic,berkovich,machine learning,optimization
10
+ Classifier: Development Status :: 3 - Alpha
11
+ Classifier: Intended Audience :: Science/Research
12
+ Classifier: Programming Language :: Python :: 3
13
+ Classifier: Topic :: Scientific/Engineering :: Artificial Intelligence
14
+ Classifier: Topic :: Scientific/Engineering :: Mathematics
15
+ Requires-Python: >=3.10
16
+ Description-Content-Type: text/markdown
17
+ License-File: LICENSE
18
+ Requires-Dist: jax
19
+ Requires-Dist: jaxtyping
20
+ Requires-Dist: sympy
21
+ Provides-Extra: test
22
+ Requires-Dist: absl-py; extra == "test"
23
+ Requires-Dist: numpy; extra == "test"
24
+ Dynamic: license-file
25
+
26
+ # padic-ml
27
+
28
+ **WORK IN PROGRESS. Paper code is being refactored into this library.
29
+ Thanks for your patience!**
30
+
31
+ This is a JAX library for differentiable training of _p_-adic neural networks,
32
+ implementing methods described in *Continuous Optimization for p-adic Models*
33
+ (arXiv 2026).
34
+
35
+ Install with `pip install padic-ml`.
36
+
37
+ **Disclaimer:** This is not an officially supported Google product.
38
+
39
+ ## Usage
40
+
41
+ `PArray` is an array primitive for "learnable" _p_-adic numbers (points in the _p_-adic injective hull $\Gamma_p$ in Berkovich space).
42
+
43
+ With radius 0 (no second argument), these become ordinary _p_-adic numbers $\mathbb{Q}_p$.
44
+
45
+ ```python
46
+ >>> import padic_ml as pml
47
+ >>> p1 = pml.array([3, 4], radius=[1, 3], p=3)
48
+ >>> p2 = pml.array([7, 1], p=3)
49
+ >>> p1*p2
50
+ PArray(unit=Array([7, 4], dtype=int32), valuation=Array([1, 0], dtype=int32), log_radius=Array([0., 1.], dtype=float32), p=3)
51
+ ```
@@ -0,0 +1,26 @@
1
+ # padic-ml
2
+
3
+ **WORK IN PROGRESS. Paper code is being refactored into this library.
4
+ Thanks for your patience!**
5
+
6
+ This is a JAX library for differentiable training of _p_-adic neural networks,
7
+ implementing methods described in *Continuous Optimization for p-adic Models*
8
+ (arXiv 2026).
9
+
10
+ Install with `pip install padic-ml`.
11
+
12
+ **Disclaimer:** This is not an officially supported Google product.
13
+
14
+ ## Usage
15
+
16
+ `PArray` is an array primitive for "learnable" _p_-adic numbers (points in the _p_-adic injective hull $\Gamma_p$ in Berkovich space).
17
+
18
+ With radius 0 (no second argument), these become ordinary _p_-adic numbers $\mathbb{Q}_p$.
19
+
20
+ ```python
21
+ >>> import padic_ml as pml
22
+ >>> p1 = pml.array([3, 4], radius=[1, 3], p=3)
23
+ >>> p2 = pml.array([7, 1], p=3)
24
+ >>> p1*p2
25
+ PArray(unit=Array([7, 4], dtype=int32), valuation=Array([1, 0], dtype=int32), log_radius=Array([0., 1.], dtype=float32), p=3)
26
+ ```
@@ -0,0 +1,31 @@
1
+ # Copyright 2026 Google LLC
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+
15
+ """padic_ml: continuous p-adic optimization on Berkovich spaces."""
16
+
17
+ from padic_ml import _array
18
+ from padic_ml import ops
19
+
20
+ __version__ = '0.0.1'
21
+
22
+ PArray = _array.PArray
23
+ array = _array.array
24
+ asarray = _array.asarray
25
+
26
+ __all__ = [
27
+ 'PArray',
28
+ 'array',
29
+ 'asarray',
30
+ 'ops',
31
+ ]
@@ -0,0 +1,284 @@
1
+ # Copyright 2026 Google LLC
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+
15
+ """Data structures for Berkovich space representation and auto-diff."""
16
+
17
+ from __future__ import annotations
18
+
19
+ import dataclasses
20
+ import functools
21
+
22
+ import jax
23
+ import jax.numpy as jnp
24
+ import jaxtyping as jt
25
+ import sympy
26
+
27
+
28
+ @functools.cache
29
+ def _is_prime(p: int) -> bool:
30
+ """Cached primality check using sympy.isprime."""
31
+ return bool(sympy.isprime(p))
32
+
33
+
34
+ def _matching_float_dtype(int_dtype: jnp.dtype) -> jnp.dtype:
35
+ """Returns the floating-point dtype of equal bitwidth to an integer dtype."""
36
+ return jnp.dtype(f'float{int_dtype.itemsize * 8}')
37
+
38
+
39
+ class IntOperand:
40
+ """Union type alias for int | jt.Int[jt.Array, Shape].
41
+
42
+ Usage:
43
+ IntOperand['*N'] -> int | jt.Int[jt.Array, '*N']
44
+ IntOperand['*#N'] -> int | jt.Int[jt.Array, '*#N']
45
+ IntOperand['...'] -> int | jt.Int[jt.Array, '...']
46
+ """
47
+
48
+ def __class_getitem__(cls, shape):
49
+ return int | jt.Int[jt.Array, shape]
50
+
51
+
52
+ class FloatOperand:
53
+ """Union type alias for float | jt.Float[jt.Array, Shape].
54
+
55
+ Usage:
56
+ FloatOperand['*N'] -> float | jt.Float[jt.Array, '*N']
57
+ FloatOperand['*#N'] -> float | jt.Float[jt.Array, '*#N']
58
+ FloatOperand['...'] -> float | jt.Float[jt.Array, '...']
59
+ """
60
+
61
+ def __class_getitem__(cls, shape):
62
+ return float | jt.Float[jt.Array, shape]
63
+
64
+
65
+ @functools.partial(
66
+ jax.tree_util.register_dataclass,
67
+ data_fields=('unit', 'valuation', 'log_radius'),
68
+ meta_fields=('p',),
69
+ )
70
+ @dataclasses.dataclass(eq=False, frozen=True, kw_only=True)
71
+ class PArray:
72
+ """DO NOT INIT DIRECTLY; use `(as)array()`. Array of 'continuous' p-adics.
73
+
74
+ These are elements zeta_{unit * p^valuation, p^log_radius} of the p-adic
75
+ convex hull of Qp. In a normalized (unit, valuation) pair, unit is coprime to
76
+ p, or (0,0) if c = 0, such that c = unit * p^valuation. Details on this
77
+ representation:
78
+ https://doc.sagemath.org/html/en/reference/padics/sage/rings/padics/tutorial.html#terminology-and-types-of-p-adics
79
+ https://flintlib.org/doc/padic.html
80
+
81
+ NOTE: With integer units, we can only represent Z[1/p] in Qp exactly. However,
82
+ this set is dense, so for non-zero radii, we can choose the center to be in
83
+ Z[1/p].
84
+
85
+ Attributes:
86
+ unit: Integer unit representative coprime to p (or 0 if center is 0). int.
87
+ valuation: Exact p-adic valuation v_p(c) (or 0 if center is 0). int.
88
+ log_radius: Log-radius of the disk. float.
89
+ p: Prime base p.
90
+ """
91
+
92
+ unit: jt.Int[jt.Array, '*N']
93
+ valuation: jt.Int[jt.Array, '*N']
94
+ log_radius: jt.Float[jt.Array, '*N']
95
+ p: int
96
+
97
+ @property
98
+ def center(self) -> jt.Int[jt.Array, '*N']:
99
+ """Reconstructs the integer center u * p^v. Requires valuation >= 0."""
100
+ p_pow = jnp.asarray(self.p, dtype=self.unit.dtype) ** jnp.maximum(
101
+ 0, self.valuation
102
+ )
103
+ return self.unit * p_pow
104
+
105
+ # The below two properties (shape and dtype) give a duck-typed array for JAX
106
+ # typing. See: https://docs.kidger.site/jaxtyping/api/array/#array
107
+
108
+ @property
109
+ def shape(self) -> tuple[int, ...]:
110
+ """Returns the shape of the array."""
111
+ return self.unit.shape
112
+
113
+ @property
114
+ def dtype(self) -> jnp.dtype:
115
+ """Returns the data type of the unit array."""
116
+ return self.unit.dtype
117
+
118
+ # Imports of ops are inside the functions to avoid circular dependency.
119
+ #
120
+ # We do not add shape annotations for these wrappers, as such annotations only
121
+ # get used in runtime type checking. We consolidate those in `ops`. Also see
122
+ # warning which discourages strings or from __future__ import annotations as
123
+ # array terms of the jt type annotation.
124
+ # https://docs.kidger.site/jaxtyping/api/runtime-type-checking/.
125
+ #
126
+ # pylint: disable=g-import-not-at-top
127
+
128
+ def __add__(self, other: PArray | IntOperand['...']) -> PArray:
129
+ from padic_ml import ops
130
+
131
+ return ops.add(self, other)
132
+
133
+ def __radd__(self, other: PArray | IntOperand['...']) -> PArray:
134
+ return self.__add__(other)
135
+
136
+ def __mul__(self, other: PArray | IntOperand['...']) -> PArray:
137
+ from padic_ml import ops
138
+
139
+ return ops.mul(self, other)
140
+
141
+ def __rmul__(self, other: PArray | IntOperand['...']) -> PArray:
142
+ return self.__mul__(other)
143
+
144
+ def __neg__(self) -> PArray:
145
+ from padic_ml import ops
146
+
147
+ return ops.neg(self)
148
+
149
+ def __pow__(self, power: int) -> PArray:
150
+ from padic_ml import ops
151
+
152
+ return ops.power(self, power)
153
+
154
+ def __sub__(self, other: PArray | IntOperand['...']) -> PArray:
155
+ from padic_ml import ops
156
+
157
+ return ops.sub(self, other)
158
+
159
+ def abs(self) -> jax.Array:
160
+ from padic_ml import ops
161
+
162
+ return ops.absolute(self)
163
+
164
+ def is_padic(self) -> jax.Array:
165
+ from padic_ml import ops
166
+
167
+ return ops.is_padic(self)
168
+
169
+ # pylint: enable=g-import-not-at-top
170
+
171
+
172
+ def array(
173
+ center: IntOperand['*N'] | None = None,
174
+ radius: FloatOperand['*#N'] | None = None,
175
+ *,
176
+ p: int,
177
+ log_radius: FloatOperand['*#N'] | None = None,
178
+ unit: IntOperand['*N'] | None = None,
179
+ valuation: IntOperand['*#N'] | None = None,
180
+ ) -> PArray:
181
+ """Constructs a PArray, validating and canonicalizing its arguments.
182
+
183
+ This is the eager entry point for building a PArray, analogous to `jnp.array`.
184
+ All validation and casework lives here rather than in `PArray.__init__`, which
185
+ must stay free of logic because JAX calls it to rebuild the pytree on every
186
+ transformation boundary.
187
+
188
+ Supported invocation modes:
189
+ 1. From an integer center:
190
+ `array(center, radius=None, *, p, log_radius=None)`
191
+ 2. From pre-decomposed unit and valuation (e.g. elements of Z[1/p]):
192
+ `array(radius=None, *, p, log_radius=None, unit=..., valuation=...)`
193
+
194
+ Args:
195
+ center: Integer center of the disk, u * p^v. If provided, unit and valuation
196
+ are computed automatically via `decompose(center, p)`.
197
+ radius: Non-negative radius r = p^log_radius of the disk. Mutually exclusive
198
+ with `log_radius`. Converted internally to `log_radius`.
199
+ p: Prime base p (must be a prime integer >= 2).
200
+ log_radius: Log-radius of the disk (base p). Defaults to -inf (a strictly
201
+ p-adic point) if both `radius` and `log_radius` are omitted.
202
+ unit: Integer unit representative coprime to p (or 0 if center is 0). Must
203
+ be provided together with `valuation` when `center` is omitted.
204
+ valuation: Exact p-adic valuation v_p(c) (or 0 if center is 0). Must be
205
+ provided together with `unit` when `center` is omitted.
206
+
207
+ Returns:
208
+ A PArray in canonical (unit, valuation, log_radius) form.
209
+
210
+ Raises:
211
+ ValueError: If p is not prime, if both `radius` and `log_radius` are given,
212
+ if `radius` is negative, if the integer arguments are not of integer
213
+ dtype, or if neither `center` nor `(unit, valuation)` is provided.
214
+ """
215
+ if p < 2 or not _is_prime(p):
216
+ raise ValueError(f'Prime base p must be a prime >= 2, got {p}.')
217
+ if radius is not None and log_radius is not None:
218
+ raise ValueError('Cannot specify both radius and log_radius.')
219
+
220
+ # Resolve the canonical (unit, valuation) pair.
221
+ if unit is not None and valuation is not None:
222
+ u = jnp.asarray(unit)
223
+ v = jnp.asarray(valuation)
224
+ if not jnp.issubdtype(u.dtype, jnp.integer):
225
+ raise ValueError(f'unit must have integer dtype, got {u.dtype}.')
226
+ if not jnp.issubdtype(v.dtype, jnp.integer):
227
+ raise ValueError(f'valuation must have integer dtype, got {v.dtype}.')
228
+ # Zero has no valuation; pin it to 0 so equal values compare equal.
229
+ v = jnp.broadcast_to(jnp.where(u == 0, 0, v), u.shape)
230
+ elif center is not None:
231
+ c = jnp.asarray(center)
232
+ if not jnp.issubdtype(c.dtype, jnp.integer):
233
+ raise ValueError(f'center must have integer dtype, got {c.dtype}.')
234
+ # Deferred to break the _array <-> ops cycle, as in the PArray operator
235
+ # methods above.
236
+ from padic_ml import ops # pylint: disable=g-import-not-at-top
237
+
238
+ u, v = ops.decompose(c, p)
239
+ else:
240
+ raise ValueError('Either center or (unit, valuation) must be provided.')
241
+
242
+ # Resolve the log-radius, matching the bitwidth of the integer payload so that
243
+ # 32-bit inputs do not silently incur 64-bit intermediates under jit.
244
+ float_dtype = _matching_float_dtype(u.dtype)
245
+ if log_radius is not None:
246
+ r = jnp.asarray(log_radius, dtype=float_dtype)
247
+ elif radius is not None:
248
+ rad = jnp.asarray(radius, dtype=float_dtype)
249
+ if jnp.any(rad < 0):
250
+ raise ValueError('Radius must be non-negative.')
251
+ log_p = jnp.log(jnp.asarray(p, dtype=float_dtype))
252
+ r = jnp.where(
253
+ rad == 0,
254
+ jnp.asarray(-jnp.inf, dtype=float_dtype),
255
+ jnp.log(rad) / log_p,
256
+ )
257
+ else:
258
+ r = jnp.full(u.shape, -jnp.inf, dtype=float_dtype)
259
+
260
+ return PArray(
261
+ unit=u, valuation=v, log_radius=jnp.broadcast_to(r, u.shape), p=p
262
+ )
263
+
264
+
265
+ @jt.jaxtyped
266
+ def asarray(
267
+ x: jt.Shaped[PArray, '*N'] | IntOperand['*N'],
268
+ *,
269
+ p: int,
270
+ ) -> jt.Shaped[PArray, '*N']:
271
+ """Converts an integer or integer array operand to a PArray with prime base p.
272
+
273
+ Idempotent on PArray inputs, analogous to `jnp.asarray`.
274
+
275
+ Raises:
276
+ ValueError: If x is a PArray whose prime base differs from p.
277
+ """
278
+ if isinstance(x, PArray):
279
+ if x.p != p:
280
+ raise ValueError(
281
+ f'Cannot convert PArray with prime base p={x.p} to p={p}.'
282
+ )
283
+ return x
284
+ return array(x, p=p)