padic-ml 0.0.1__py3-none-any.whl

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/__init__.py ADDED
@@ -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
+ ]
padic_ml/_array.py ADDED
@@ -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)
@@ -0,0 +1,180 @@
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
+ from absl.testing import absltest
16
+ import jax
17
+ import jax.numpy as jnp
18
+ import numpy as np
19
+ import padic_ml as pml
20
+ from padic_ml import _array
21
+
22
+ PArray = _array.PArray
23
+ array = pml.array
24
+
25
+
26
+ class PArrayTest(absltest.TestCase):
27
+ """PArray methods that are stubs in _array.py are tested in ops_test.py."""
28
+
29
+ def test_init(self):
30
+ # Default log_radius is -inf
31
+ arr = array(jnp.array([1, 2]), p=3)
32
+ np.testing.assert_array_equal(arr.center, jnp.array([1, 2]))
33
+ np.testing.assert_array_equal(
34
+ arr.log_radius, jnp.array([-jnp.inf, -jnp.inf])
35
+ )
36
+ self.assertEqual(arr.p, 3)
37
+
38
+ # Casts inputs to array
39
+ arr = array([1, 2], p=2)
40
+ self.assertIsInstance(arr.center, jax.Array)
41
+ np.testing.assert_array_equal(arr.center, jnp.array([1, 2]))
42
+
43
+ # Broadcasts radius inputs (r=4.0 at p=2 -> log_radius=2.0)
44
+ arr = array(jnp.array([1, 2]), 4.0, p=2)
45
+ self.assertIsInstance(arr.log_radius, jax.Array)
46
+ np.testing.assert_allclose(arr.log_radius, jnp.array([2.0, 2.0]))
47
+
48
+ # Radius 0.0 converts to log_radius -inf
49
+ arr_zero_rad = array(jnp.array([1, 2]), 0.0, p=2)
50
+ np.testing.assert_array_equal(
51
+ arr_zero_rad.log_radius, jnp.array([-jnp.inf, -jnp.inf])
52
+ )
53
+
54
+ # Keyword log_radius input
55
+ arr_log = array(jnp.array([1, 2]), log_radius=1.0, p=2)
56
+ np.testing.assert_array_equal(arr_log.log_radius, jnp.array([1.0, 1.0]))
57
+
58
+ def test_construction_and_properties(self):
59
+ x = array(jnp.array([1, 2, 3], dtype=jnp.int32), p=5)
60
+ self.assertEqual(x.shape, (3,))
61
+ self.assertEqual(x.dtype, jnp.dtype(jnp.int32))
62
+ self.assertEqual(x.p, 5)
63
+
64
+ def test_unit_valuation_init(self):
65
+ # Eager canonicalization of integer centers
66
+ arr = array(45, p=3)
67
+ np.testing.assert_array_equal(arr.unit, jnp.array(5))
68
+ np.testing.assert_array_equal(arr.valuation, jnp.array(2))
69
+ np.testing.assert_array_equal(arr.center, jnp.array(45))
70
+
71
+ # Exact zero center (u=0, v=0)
72
+ zero = array(0, p=3)
73
+ np.testing.assert_array_equal(zero.unit, jnp.array(0))
74
+ np.testing.assert_array_equal(zero.valuation, jnp.array(0))
75
+ np.testing.assert_array_equal(zero.center, jnp.array(0))
76
+
77
+ # Negative integer center
78
+ neg_arr = array(-12, p=3)
79
+ np.testing.assert_array_equal(neg_arr.unit, jnp.array(-4))
80
+ np.testing.assert_array_equal(neg_arr.valuation, jnp.array(1))
81
+ np.testing.assert_array_equal(neg_arr.center, jnp.array(-12))
82
+
83
+ # Pre-decomposed unit/valuation (Z[1/p] representation)
84
+ frac = array(unit=2, valuation=-3, p=3)
85
+ np.testing.assert_array_equal(frac.unit, jnp.array(2))
86
+ np.testing.assert_array_equal(frac.valuation, jnp.array(-3))
87
+
88
+ # Pre-decomposed with log-radius
89
+ disk = array(unit=5, valuation=2, log_radius=-1.0, p=3)
90
+ np.testing.assert_array_equal(disk.center, jnp.array(45))
91
+ np.testing.assert_array_equal(disk.log_radius, jnp.array(-1.0))
92
+
93
+ def test_center_clamps_negative_valuation(self):
94
+ """Documents (does not endorse) the .center precondition.
95
+
96
+ 2 * 3^-3 is not an integer, so there is no correct integer to return. The
97
+ property clamps to p^max(0, v) and thus reports the unit. This is asserted
98
+ so the documented precondition stays honest rather than drifting silently;
99
+ exact work must use (unit, valuation).
100
+ """
101
+ frac = array(unit=2, valuation=-3, p=3)
102
+ np.testing.assert_array_equal(frac.center, jnp.array(2))
103
+
104
+ def test_direct_construction_accepts_float0(self):
105
+ """The canonical constructor must not validate dtypes.
106
+
107
+ `jax.grad(..., allow_int=True)` assigns float0 tangents to integer leaves
108
+ and then rebuilds the pytree by calling this constructor. A dtype assertion
109
+ here would reject JAX's own gradient machinery, so this must not raise.
110
+ """
111
+ float0 = jax.dtypes.float0
112
+ zero = np.zeros((), dtype=float0)
113
+ arr = PArray(
114
+ unit=zero,
115
+ valuation=zero,
116
+ log_radius=jnp.asarray(-jnp.inf),
117
+ p=3,
118
+ )
119
+ self.assertEqual(arr.unit.dtype, float0)
120
+
121
+ def test_init_error(self):
122
+ # Raising ValueError when neither center nor (unit, valuation) is passed
123
+ with self.assertRaises(ValueError):
124
+ array(p=3)
125
+ # Raising ValueError when only unit is passed
126
+ with self.assertRaises(ValueError):
127
+ array(unit=5, p=3)
128
+ # Raising ValueError when only valuation is passed
129
+ with self.assertRaises(ValueError):
130
+ array(valuation=2, p=3)
131
+ # Raising ValueError when not prime
132
+ with self.assertRaises(ValueError):
133
+ array(5, p=1)
134
+ with self.assertRaises(ValueError):
135
+ array(5, p=4)
136
+ with self.assertRaises(ValueError):
137
+ array(5, p=9)
138
+ # Raising ValueError when center is not integer dtype
139
+ with self.assertRaises(ValueError):
140
+ array(1.5, p=3)
141
+ # Raising ValueError when unit or valuation is not integer dtype
142
+ with self.assertRaises(ValueError):
143
+ array(unit=1.5, valuation=2, p=3)
144
+ with self.assertRaises(ValueError):
145
+ array(unit=1, valuation=2.5, p=3)
146
+ # Raising ValueError when both radius and log_radius are specified
147
+ with self.assertRaises(ValueError):
148
+ array(5, 1.0, log_radius=0.0, p=3)
149
+ # Raising ValueError when radius is negative
150
+ with self.assertRaises(ValueError):
151
+ array(5, -1.0, p=3)
152
+
153
+ def test_pytree_round_trip(self):
154
+ """register_dataclass must rebuild an identical PArray from its leaves.
155
+
156
+ This is the container contract the logic-free constructor exists to serve:
157
+ JAX calls it via `unflatten_func` on every transformation boundary.
158
+ """
159
+ x = array(45, log_radius=-1.0, p=3)
160
+ leaves, treedef = jax.tree_util.tree_flatten(x)
161
+ y = jax.tree_util.tree_unflatten(treedef, leaves)
162
+ self.assertEqual(y.unit, x.unit)
163
+ self.assertEqual(y.valuation, x.valuation)
164
+ self.assertEqual(y.log_radius, x.log_radius)
165
+ self.assertEqual(y.p, x.p)
166
+
167
+ def test_asarray(self):
168
+ # Idempotent on PArray inputs
169
+ x = array(45, p=3)
170
+ self.assertIs(pml.asarray(x, p=3), x)
171
+ # Converts integer operands
172
+ converted = pml.asarray(45, p=3)
173
+ np.testing.assert_array_equal(converted.unit, jnp.array(5))
174
+ # Rejects a prime-base mismatch
175
+ with self.assertRaises(ValueError):
176
+ pml.asarray(x, p=5)
177
+
178
+
179
+ if __name__ == '__main__':
180
+ absltest.main()
padic_ml/ops.py ADDED
@@ -0,0 +1,256 @@
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
+ """Functional arithmetic operations for PArray (Berkovich disk algebra).
16
+
17
+ Architecture and Conventions:
18
+ -----------------------------
19
+ 1. Container + Functional Math Separation:
20
+ - `PArray` (defined in `_array.py`) is the Berkovich disk container.
21
+ - It delegates to the arithmetic logic here (the functional `ops.*` API).
22
+
23
+ 2. Type Enforcement via jaxtyping:
24
+ - `ops.*` functions are decorated with `@jt.jaxtyped` to enforce dtype
25
+ contracts and broadcasting rules (`*#N -> *N`) across operands.
26
+
27
+ 3. Subclass and Custom Type Construction Contract:
28
+ - Each arithmetic implementation explicitly constructs and returns a base
29
+ `PArray(unit=..., valuation=..., log_radius=..., p=...)`. That constructor
30
+ is canonical-only and keyword-only; it performs no validation, because JAX
31
+ calls it to rebuild the pytree on every transformation boundary.
32
+ - To build a PArray from a center, a radius, or a plain integer operand, use
33
+ `_array.array(...)` or `_array.asarray(...)` instead.
34
+ - Subclasses (e.g. `LegacyPArray`) override the relevant operator
35
+ methods, call `super()` or `ops.*` for the base container, and
36
+ explicitly construct their own class instance.
37
+ """
38
+
39
+ import functools
40
+ import math
41
+
42
+ import jax
43
+ import jax.numpy as jnp
44
+ import jaxtyping as jt
45
+ from padic_ml import _array
46
+
47
+ IntOperand = _array.IntOperand
48
+ PArray = _array.PArray
49
+
50
+
51
+ @jt.jaxtyped
52
+ def absolute(x: jt.Shaped[PArray, '*N']) -> jt.Float[jax.Array, '*N']:
53
+ """Computes the p-adic norm |x|_p = p^{-v_p(x)} (0 if unit == 0)."""
54
+ # log_radius already carries the float dtype matching the integer payload.
55
+ float_dtype = x.log_radius.dtype
56
+ return jnp.where(
57
+ x.unit == 0,
58
+ jnp.asarray(0.0, dtype=float_dtype),
59
+ jnp.asarray(x.p, dtype=float_dtype) ** (-x.valuation),
60
+ )
61
+
62
+
63
+ @jt.jaxtyped
64
+ def is_padic(x: jt.Shaped[PArray, '*N']) -> jt.Bool[jax.Array, '*N']:
65
+ """Checks if the array is strictly p-adic (log_radius -inf)."""
66
+ return jnp.isneginf(x.log_radius)
67
+
68
+
69
+ @jt.jaxtyped
70
+ def add(
71
+ a: jt.Shaped[PArray, '*#N'],
72
+ b: jt.Shaped[PArray, '*#N'] | IntOperand['*#N'],
73
+ ) -> jt.Shaped[PArray, '*N']:
74
+ """Translates the center of a Berkovich disk."""
75
+
76
+ if isinstance(b, PArray):
77
+ if a.p != b.p:
78
+ raise ValueError(
79
+ f'Addition between PArrays with different primes {a.p} and {b.p} is'
80
+ ' not supported.'
81
+ )
82
+ if is_padic(b):
83
+ return add(a, b.center)
84
+ elif is_padic(a):
85
+ return add(b, a.center)
86
+ else:
87
+ raise NotImplementedError(
88
+ 'Addition between two PArrays with positive radii is not supported'
89
+ ' outside computation graphs.'
90
+ )
91
+
92
+ return _array.array(a.center + b, log_radius=a.log_radius, p=a.p)
93
+
94
+
95
+ @jt.jaxtyped
96
+ def mul(
97
+ a: jt.Shaped[PArray, '*#N'],
98
+ b: jt.Shaped[PArray, '*#N'] | IntOperand['*#N'],
99
+ ) -> jt.Shaped[PArray, '*N']:
100
+ """Multiplicativity of seminorms on the Berkovich line."""
101
+ b = _array.asarray(b, p=a.p)
102
+ new_unit = a.unit * b.unit
103
+ new_valuation = jnp.where(new_unit == 0, 0, a.valuation + b.valuation)
104
+
105
+ term_one = jnp.where(
106
+ a.unit == 0,
107
+ -jnp.inf,
108
+ -a.valuation.astype(b.log_radius.dtype) + b.log_radius,
109
+ )
110
+ term_two = jnp.where(
111
+ b.unit == 0,
112
+ -jnp.inf,
113
+ -b.valuation.astype(a.log_radius.dtype) + a.log_radius,
114
+ )
115
+ term_three = a.log_radius + b.log_radius
116
+
117
+ new_log_radius = jnp.maximum(jnp.maximum(term_one, term_two), term_three)
118
+ return PArray(
119
+ unit=new_unit,
120
+ valuation=new_valuation,
121
+ log_radius=new_log_radius,
122
+ p=a.p,
123
+ )
124
+
125
+
126
+ @jt.jaxtyped
127
+ def neg(a: jt.Shaped[PArray, '*N']) -> jt.Shaped[PArray, '*N']:
128
+ """Negation on Berkovich disk."""
129
+ return mul(a, -1)
130
+
131
+
132
+ @jt.jaxtyped
133
+ def power(a: jt.Shaped[PArray, '*N'], exponent: int) -> jt.Shaped[PArray, '*N']:
134
+ """Integer power on the Berkovich line via binomial expansion."""
135
+
136
+ new_unit = a.unit**exponent
137
+ new_valuation = jnp.where(new_unit == 0, 0, a.valuation * exponent)
138
+
139
+ terms_list = []
140
+ for k in range(1, exponent + 1):
141
+ coefficient = math.comb(exponent, k)
142
+ _, v_comb = decompose(coefficient, a.p)
143
+ is_zero_term = (a.unit == 0) & (k < exponent)
144
+ v_term = v_comb + (exponent - k) * a.valuation
145
+ term_log_radius = jnp.where(
146
+ is_zero_term,
147
+ -jnp.inf,
148
+ -v_term.astype(a.log_radius.dtype) + k * a.log_radius,
149
+ )
150
+ terms_list.append(term_log_radius)
151
+
152
+ terms_stacked = jnp.stack(terms_list, axis=0)
153
+ new_log_radius = jnp.max(terms_stacked, axis=0)
154
+
155
+ return PArray(
156
+ unit=new_unit,
157
+ valuation=new_valuation,
158
+ log_radius=new_log_radius,
159
+ p=a.p,
160
+ )
161
+
162
+
163
+ @jt.jaxtyped
164
+ def sub(
165
+ a: jt.Shaped[PArray, '*#N'],
166
+ b: jt.Shaped[PArray, '*#N'] | IntOperand['*#N'],
167
+ ) -> jt.Shaped[PArray, '*N']:
168
+ """Subtraction on Berkovich disk."""
169
+ return add(a, -b)
170
+
171
+
172
+ # ---------------------------------------------------------------------------
173
+ # Non-PArray utility functions
174
+ # ---------------------------------------------------------------------------
175
+
176
+
177
+ @functools.cache
178
+ def _max_valuation(p: int, dtype: jnp.dtype) -> int:
179
+ """Maximum p-adic valuation representable by an integer dtype.
180
+
181
+ Computes floor(log_p(max_val)) using integer arithmetic to avoid
182
+ floating-point precision issues with math.log.
183
+
184
+ Args:
185
+ p: Prime base.
186
+ dtype: Integer dtype whose range bounds the valuation.
187
+
188
+ Returns:
189
+ The largest v such that p^v fits within the dtype's range.
190
+ """
191
+ v, n = 0, jnp.iinfo(dtype).max
192
+ while n >= p:
193
+ n //= p
194
+ v += 1
195
+ return v
196
+
197
+
198
+ @jt.jaxtyped
199
+ def decompose(
200
+ x: IntOperand['*N'],
201
+ p: int,
202
+ ) -> tuple[jt.Int[jt.Array, '*N'], jt.Int[jt.Array, '*N']]:
203
+ """Decomposes an integer array into canonical (unit, valuation) pair.
204
+
205
+ For each element, factors x = u * p^v such that p does not divide u
206
+ (or u = 0, v = 0 if x = 0).
207
+
208
+ Uses fori_loop with a static bound (the maximum valuation for the input
209
+ dtype) instead of while_loop. This eliminates the per-iteration jnp.any()
210
+ global synchronization barrier that while_loop's cond_fun requires, making
211
+ each iteration purely element-wise.
212
+
213
+ Returns:
214
+ (unit, valuation): unit tensor u in Z and int valuation tensor v in Z.
215
+ """
216
+ x_arr = jnp.asarray(x)
217
+ abs_x = jnp.abs(x_arr)
218
+ is_zero = abs_x == 0
219
+ # Replace zeros with 1 to avoid division-by-zero in the loop body.
220
+ safe_x = jnp.where(is_zero, 1, abs_x)
221
+
222
+ def body_fun(_, state):
223
+ curr_x, val = state
224
+ divisible = curr_x % p == 0
225
+ # Only divide elements still divisible by p; others pass through.
226
+ next_x = jnp.where(divisible, curr_x // p, curr_x)
227
+ next_val = jnp.where(divisible, val + 1, val)
228
+ return next_x, next_val
229
+
230
+ # Upper bound on iterations: no integer of this dtype can have a p-adic
231
+ # valuation exceeding this, so the loop is guaranteed to finish all elements.
232
+ max_iters = _max_valuation(p, x_arr.dtype)
233
+ init_val = jnp.zeros_like(safe_x)
234
+ final_x, final_val = jax.lax.fori_loop(
235
+ 0, max_iters, body_fun, (safe_x, init_val)
236
+ )
237
+
238
+ # Restore sign and canonicalize zeros to (u=0, v=0).
239
+ unit = jnp.where(is_zero, 0, jnp.sign(x_arr) * final_x)
240
+ valuation = jnp.where(is_zero, 0, final_val)
241
+ return unit, valuation
242
+
243
+
244
+ @jt.jaxtyped
245
+ def to_expansion(
246
+ value: int | jt.Int[jt.Array, ''],
247
+ p: int,
248
+ terms: int = 8,
249
+ ) -> str:
250
+ """Formats a standard integer into a p-adic string for representation."""
251
+ value_modulo = int(value) % (p**terms)
252
+ digits_list = []
253
+ for _ in range(terms):
254
+ digits_list.append(str(value_modulo % p))
255
+ value_modulo //= p
256
+ return '...' + ''.join(reversed(digits_list))
padic_ml/ops_test.py ADDED
@@ -0,0 +1,351 @@
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
+ """Unit tests for PArray and p-adic operations in ops module."""
16
+
17
+ from absl.testing import absltest
18
+ from absl.testing import parameterized
19
+ import itertools
20
+ import jax
21
+ import jax.numpy as jnp
22
+ import numpy as np
23
+ import padic_ml as pml
24
+ from padic_ml import ops
25
+
26
+ PArray = pml.PArray
27
+ array = pml.array
28
+
29
+
30
+ class OpsTest(absltest.TestCase):
31
+ """Tests for PArray dataclass and p-adic operations."""
32
+
33
+ def test_absolute(self):
34
+ # |9|_3 = 3^{-2} = 1/9
35
+ nine = array(jnp.array(9), p=3)
36
+ self.assertAlmostEqual(nine.abs(), 1.0 / 9.0)
37
+ self.assertAlmostEqual(ops.absolute(nine), 1.0 / 9.0)
38
+
39
+ # |5|_3 = 3^{-0} = 1
40
+ five = array(jnp.array(5), p=3)
41
+ self.assertAlmostEqual(five.abs(), 1.0)
42
+ self.assertAlmostEqual(ops.absolute(five), 1.0)
43
+
44
+ # |0|_3 = 0.0
45
+ zero = array(jnp.array(0), p=3)
46
+ self.assertAlmostEqual(zero.abs(), 0.0)
47
+ self.assertAlmostEqual(ops.absolute(zero), 0.0)
48
+
49
+ def test_absolute_dtype_x64(self):
50
+ """|x|_p preserves the input bitwidth instead of upcasting to float64.
51
+
52
+ Deliberately runs under `jax.enable_x64(True)`: in JAX's default x32 mode
53
+ float64 is unreachable, so asserting a float32 result would be vacuous.
54
+ """
55
+ with jax.enable_x64(True):
56
+ arr32 = array(jnp.array([9, 0, 5], dtype=jnp.int32), p=3)
57
+ self.assertEqual(ops.absolute(arr32).dtype, jnp.float32)
58
+
59
+ arr64 = array(jnp.array([9, 0, 5], dtype=jnp.int64), p=3)
60
+ self.assertEqual(ops.absolute(arr64).dtype, jnp.float64)
61
+
62
+ def test_asarray(self):
63
+ # asarray now lives in _array.py and is exported as pml.asarray; ops no
64
+ # longer re-exports it (container/math separation).
65
+ self.assertFalse(hasattr(ops, 'asarray'))
66
+
67
+ # Converts int to PArray with prime p
68
+ arr = pml.asarray(9, p=3)
69
+ self.assertIsInstance(arr, PArray)
70
+ self.assertEqual(arr.unit, 1)
71
+ self.assertEqual(arr.valuation, 2)
72
+ self.assertEqual(arr.p, 3)
73
+
74
+ # Returns existing PArray unchanged if p matches
75
+ same = pml.asarray(arr, p=3)
76
+ self.assertIs(same, arr)
77
+
78
+ # Raises ValueError if prime p mismatches
79
+ with self.assertRaises(ValueError):
80
+ pml.asarray(arr, p=5)
81
+
82
+ def test_is_padic(self):
83
+ a = array(jnp.array([1, 2]), log_radius=jnp.array([-1.0, -2.0]), p=2)
84
+ np.testing.assert_array_equal(a.is_padic(), jnp.array([False, False]))
85
+ np.testing.assert_array_equal(ops.is_padic(a), jnp.array([False, False]))
86
+
87
+ b = array(jnp.array([1, 2]), log_radius=jnp.array([3.0, -jnp.inf]), p=3)
88
+ np.testing.assert_array_equal(b.is_padic(), jnp.array([False, True]))
89
+ np.testing.assert_array_equal(ops.is_padic(b), jnp.array([False, True]))
90
+
91
+ # Default log_radius is -inf, so is_padic is True.
92
+ c = array(jnp.array([1, 2]), p=3)
93
+ np.testing.assert_array_equal(c.is_padic(), jnp.array(True))
94
+ np.testing.assert_array_equal(ops.is_padic(c), jnp.array(True))
95
+
96
+ def test_add(self):
97
+ # Scalar translation: center translated, log_radius unchanged
98
+ a = array(5, log_radius=-2.0, p=3)
99
+ res_scalar = a + 4
100
+ self.assertEqual(res_scalar.unit, 1)
101
+ self.assertEqual(res_scalar.valuation, 2)
102
+ self.assertEqual(res_scalar.log_radius, -2.0)
103
+
104
+ res_scalar_fn = ops.add(a, 4)
105
+ self.assertEqual(res_scalar_fn.unit, 1)
106
+ self.assertEqual(res_scalar_fn.valuation, 2)
107
+ self.assertEqual(res_scalar_fn.log_radius, -2.0)
108
+
109
+ # Left scalar addition:
110
+ res_left = 4 + a
111
+ self.assertEqual(res_left.unit, 1)
112
+ self.assertEqual(res_left.valuation, 2)
113
+ self.assertEqual(res_left.log_radius, -2.0)
114
+
115
+ # Point + Disk translation:
116
+ b = array(3, log_radius=-jnp.inf, p=3)
117
+ res_point = a + b
118
+ self.assertEqual(res_point.unit, 8)
119
+ self.assertEqual(res_point.valuation, 0)
120
+ self.assertEqual(res_point.log_radius, -2.0)
121
+
122
+ # Two positive radii disks should raise NotImplementedError:
123
+ c = array(3, log_radius=-1.0, p=3)
124
+ with self.assertRaises(NotImplementedError):
125
+ _ = a + c
126
+ with self.assertRaises(NotImplementedError):
127
+ ops.add(a, c)
128
+
129
+ def test_commutativity(self):
130
+ """Addition is commutative: a+b == b+a in unit, valuation, and log_radius."""
131
+ a = array(5, log_radius=-2.0, p=3)
132
+ b = array(3, log_radius=-jnp.inf, p=3)
133
+ ab = a + b
134
+ ba = b + a
135
+ np.testing.assert_allclose(ab.log_radius, ba.log_radius)
136
+ np.testing.assert_allclose(ab.unit, ba.unit)
137
+ np.testing.assert_allclose(ab.valuation, ba.valuation)
138
+
139
+ def test_mul_cross_terms(self):
140
+ """Verify that mul accounts for cross terms in radius."""
141
+ x = array(1, log_radius=-2.0, p=3)
142
+ y = array(1, log_radius=-3.0, p=3)
143
+ f = x * y
144
+ # max(v_1*(-1)+rho_2, v_2*(-1)+rho_1, rho_1 +rho_2) = max(-3,-2,-5) = -2.0
145
+ self.assertAlmostEqual(f.log_radius, -2.0)
146
+ self.assertEqual(f.unit, 1)
147
+ self.assertEqual(f.valuation, 0)
148
+
149
+ # Scalar multiplication:
150
+ f_scalar = x * 9 # v_3(9) = 2 -> rho - v = -2 - 2 = -4.0
151
+ self.assertEqual(f_scalar.unit, 1)
152
+ self.assertEqual(f_scalar.valuation, 2)
153
+ self.assertAlmostEqual(f_scalar.log_radius, -4.0)
154
+
155
+ f_scalar_left = 9 * x
156
+ self.assertEqual(f_scalar_left.unit, 1)
157
+ self.assertEqual(f_scalar_left.valuation, 2)
158
+ self.assertAlmostEqual(f_scalar_left.log_radius, -4.0)
159
+
160
+ # Pre-decomposed Z[1/p] multiplication
161
+ frac_a = array(unit=2, valuation=-3, p=3) # 2/27
162
+ frac_b = array(unit=5, valuation=2, p=3) # 45
163
+ prod = frac_a * frac_b
164
+ self.assertEqual(prod.unit, 10)
165
+ self.assertEqual(prod.valuation, -1)
166
+ self.assertTrue(jnp.isneginf(prod.log_radius))
167
+
168
+ def test_power(self):
169
+ """Verify that pow accounts for cross terms in radius."""
170
+ # c=1, rho=-2.0
171
+ x = array(1, log_radius=-2.0, p=3)
172
+ f = x**2
173
+ # Correct radius: max(log|2c| + rho, 2*rho) = max(0 - 2, -4) = -2.0
174
+ self.assertAlmostEqual(f.log_radius, -2.0)
175
+ self.assertEqual(f.unit, 1)
176
+ self.assertEqual(f.valuation, 0)
177
+
178
+ # Power with non-trivial unit and valuation: 45 = 5 * 3^2
179
+ a = array(45, log_radius=-1.0, p=3)
180
+ a2 = a**2
181
+ self.assertEqual(a2.unit, 25)
182
+ self.assertEqual(a2.valuation, 4)
183
+
184
+ a3 = a**3
185
+ self.assertEqual(a3.unit, 125)
186
+ self.assertEqual(a3.valuation, 6)
187
+
188
+ def test_zero_edge_cases(self):
189
+ """Verify operations involving exact zeros (u=0, v=0)."""
190
+ zero = array(0, p=3)
191
+ five = array(5, p=3)
192
+
193
+ # Zero * Non-zero PArray
194
+ mul_zero = zero * five
195
+ self.assertEqual(mul_zero.unit, 0)
196
+ self.assertEqual(mul_zero.valuation, 0)
197
+ self.assertTrue(jnp.isneginf(mul_zero.log_radius))
198
+
199
+ # Non-zero * Scalar 0
200
+ scalar_zero = five * 0
201
+ self.assertEqual(scalar_zero.unit, 0)
202
+ self.assertEqual(scalar_zero.valuation, 0)
203
+ self.assertTrue(jnp.isneginf(scalar_zero.log_radius))
204
+
205
+ # Zero + Non-zero PArray
206
+ add_zero = zero + five
207
+ self.assertEqual(add_zero.unit, 5)
208
+ self.assertEqual(add_zero.valuation, 0)
209
+
210
+ # Power of zero
211
+ pow_zero = zero**2
212
+ self.assertEqual(pow_zero.unit, 0)
213
+ self.assertEqual(pow_zero.valuation, 0)
214
+
215
+ def test_cancellation_cases(self):
216
+ """Verify p-adic cancellation dynamics in addition and multiplication."""
217
+ # --- Addition Cancellation (valuation jumps) ---
218
+ # 1 + 2 = 3 at p=3: valuation jumps from 0 to 1
219
+ a = array(1, p=3)
220
+ b = array(2, p=3)
221
+ sum_ab = a + b
222
+ self.assertEqual(sum_ab.unit, 1)
223
+ self.assertEqual(sum_ab.valuation, 1)
224
+
225
+ # 5 + 4 = 9 = 1 * 3^2 at p=3: valuation jumps from 0 to 2
226
+ c = array(5, p=3)
227
+ d = array(4, p=3)
228
+ sum_cd = c + d
229
+ self.assertEqual(sum_cd.unit, 1)
230
+ self.assertEqual(sum_cd.valuation, 2)
231
+
232
+ # Complete cancellation to exact 0: 5 + (-5) = 0
233
+ neg_c = array(-5, p=3)
234
+ sum_zero = c + neg_c
235
+ self.assertEqual(sum_zero.unit, 0)
236
+ self.assertEqual(sum_zero.valuation, 0)
237
+
238
+ # --- Multiplication: Euclid's lemma guarantees NO cancellation ---
239
+ # (4 * 3^1) * (5 * 3^2) = 20 * 3^3 = 540
240
+ m1 = array(12, p=3) # u=4, v=1
241
+ m2 = array(45, p=3) # u=5, v=2
242
+ prod = m1 * m2 # u=20, v=3
243
+ self.assertEqual(prod.unit, 20)
244
+ self.assertEqual(prod.valuation, 3)
245
+
246
+ def test_neg_and_sub(self):
247
+ a = array(5, log_radius=-2.0, p=3)
248
+ neg_a = -a
249
+ self.assertEqual(neg_a.unit, -5)
250
+ self.assertEqual(neg_a.valuation, 0)
251
+ self.assertEqual(neg_a.log_radius, -2.0)
252
+ self.assertEqual(ops.neg(a).unit, -5)
253
+ self.assertEqual(ops.neg(a).valuation, 0)
254
+
255
+ diff = a - 2
256
+ self.assertEqual(diff.unit, 1)
257
+ self.assertEqual(diff.valuation, 1)
258
+ self.assertEqual(diff.log_radius, -2.0)
259
+
260
+ diff_fn = ops.sub(a, 2)
261
+ self.assertEqual(diff_fn.unit, 1)
262
+ self.assertEqual(diff_fn.valuation, 1)
263
+ self.assertEqual(diff_fn.log_radius, -2.0)
264
+
265
+ def test_to_expansion(self):
266
+ exp = ops.to_expansion(14, p=3, terms=4)
267
+ self.assertEqual(exp, '...0112')
268
+
269
+
270
+ class DecomposeTest(absltest.TestCase):
271
+ """Tests for decompose edge cases and fori_loop bound assumptions."""
272
+
273
+ def test_max_representable_power_int32(self):
274
+ """Validates the fori_loop bound adapts to int32 dtype."""
275
+ max_v = ops._max_valuation(3, jnp.dtype(jnp.int32))
276
+ val = 3**max_v
277
+ u, v = ops.decompose(jnp.array(val, dtype=jnp.int32), p=3)
278
+ np.testing.assert_array_equal(u, jnp.array(1, dtype=jnp.int32))
279
+ np.testing.assert_array_equal(v, jnp.array(max_v, dtype=jnp.int32))
280
+
281
+ def test_max_representable_power_int64(self):
282
+ """Validates fori_loop bound for int64 using jax.enable_x64 context."""
283
+ with jax.enable_x64():
284
+ max_v = ops._max_valuation(3, jnp.dtype(jnp.int64))
285
+ val = 3**max_v
286
+ u, v = ops.decompose(jnp.array(val, dtype=jnp.int64), p=3)
287
+ np.testing.assert_array_equal(u, jnp.array(1, dtype=jnp.int64))
288
+ np.testing.assert_array_equal(v, jnp.array(max_v, dtype=jnp.int64))
289
+
290
+ def test_coprime_to_p(self):
291
+ """Value coprime to p should have valuation 0."""
292
+ u, v = ops.decompose(jnp.array(7), p=3)
293
+ np.testing.assert_array_equal(u, jnp.array(7))
294
+ np.testing.assert_array_equal(v, jnp.array(0))
295
+
296
+ def test_batch_mixed_valuations(self):
297
+ """Validates vectorized decomposition across varied elements."""
298
+ x = jnp.array([1, 3, 3**5, 0, -(3**3)])
299
+ u, v = ops.decompose(x, p=3)
300
+ np.testing.assert_array_equal(u, jnp.array([1, 1, 1, 0, -1]))
301
+ np.testing.assert_array_equal(v, jnp.array([0, 1, 5, 0, 3]))
302
+
303
+ def test_max_valuation_values(self):
304
+ """Verifies _max_valuation returns correct bounds for known cases."""
305
+ # 2^62 fits in int64 (max 2^63-1); 2^63 does not.
306
+ self.assertEqual(ops._max_valuation(2, jnp.dtype(jnp.int64)), 62)
307
+ # 2^30 fits in int32 (max 2^31-1); 2^31 does not.
308
+ self.assertEqual(ops._max_valuation(2, jnp.dtype(jnp.int32)), 30)
309
+ # 3^39 fits in int64; 3^40 does not.
310
+ self.assertEqual(ops._max_valuation(3, jnp.dtype(jnp.int64)), 39)
311
+
312
+
313
+ class BitwidthTest(parameterized.TestCase):
314
+ """No operation may introduce a 64-bit intermediate for a 32-bit PArray.
315
+
316
+ A silent float64 upcast (classically from `jnp.float_`, which is float64
317
+ under x64) stays numerically correct while doubling memory traffic, and f64
318
+ is emulated on TPU. No correctness test would catch it, hence this
319
+ white-box scan of the traced jaxpr.
320
+
321
+ These run under `jax.enable_x64(True)` on purpose: in the default x32 mode
322
+ float64 is unreachable, so the assertion would hold vacuously.
323
+
324
+ `neg` and `sub` are omitted because they are defined as `mul(a, -1)` and
325
+ `add(a, -b)`, so they are covered transitively. `is_padic` returns bool and
326
+ `to_expansion` is pure Python.
327
+ """
328
+
329
+ @parameterized.named_parameters(
330
+ ('absolute', ops.absolute),
331
+ ('mul', lambda x: ops.mul(x, x)),
332
+ ('power', lambda x: ops.power(x, 3)),
333
+ )
334
+ def test_no_64bit_intermediates(self, op_fn):
335
+ with jax.enable_x64(True):
336
+ arr32 = array(jnp.array([9, 0, 5], dtype=jnp.int32), p=3)
337
+ jaxpr = jax.make_jaxpr(op_fn)(arr32)
338
+ eqn_vars = itertools.chain.from_iterable(
339
+ (*eqn.invars, *eqn.outvars) for eqn in jaxpr.jaxpr.eqns
340
+ )
341
+ eqn_dtypes = {v.aval.dtype for v in eqn_vars}
342
+ const_dtypes = {c.dtype for c in jaxpr.consts}
343
+ self.assertEmpty(
344
+ (eqn_dtypes | const_dtypes) & {jnp.float64, jnp.int64},
345
+ f'64-bit types in a 32-bit jaxpr: eqns={eqn_dtypes},'
346
+ f' consts={const_dtypes}',
347
+ )
348
+
349
+
350
+ if __name__ == '__main__':
351
+ absltest.main()
@@ -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,10 @@
1
+ padic_ml/__init__.py,sha256=Rqkja26Jw6CbOLw_LiFvIb8Q95T1l-4-YyAjYOrwmA8,858
2
+ padic_ml/_array.py,sha256=CUYLnUq5VEv3uYGjdh6b9givc824XezLaMThNAK7qHM,9692
3
+ padic_ml/_array_test.py,sha256=T81P0tMXrlOLHMKVIr2cAxEN16hJjZ5uJjKYP_-bmSc,6748
4
+ padic_ml/ops.py,sha256=WGIFxNYeo58EOHU7ZVEVJxi2M0G5H13NGX5MgyYqhLw,8058
5
+ padic_ml/ops_test.py,sha256=7-2DyNrLsIzxMRAdOGSWwGR0B-dOPsY_vkaT87QFYDs,12709
6
+ padic_ml-0.0.1.dist-info/licenses/LICENSE,sha256=WNHhf_5RCaeuKWyq_K39vmp9F28LxKsB4SpomwSZ2L0,11357
7
+ padic_ml-0.0.1.dist-info/METADATA,sha256=2S-9Ajyr80SuhxudZupYbd1lrUn7HizR-wbLUWuMyqk,1809
8
+ padic_ml-0.0.1.dist-info/WHEEL,sha256=YVMoNqKzERt-wjUZwJ33xBGAwnFl-4cqbYkTtWa4itE,91
9
+ padic_ml-0.0.1.dist-info/top_level.txt,sha256=92BzyjCUXoO7eBjy-dFHwZ9A2Y020GwzbWIMcN5Zk6s,9
10
+ padic_ml-0.0.1.dist-info/RECORD,,
@@ -0,0 +1,5 @@
1
+ Wheel-Version: 1.0
2
+ Generator: setuptools (84.0.0)
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
5
+
@@ -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 @@
1
+ padic_ml