taktiny 0.0.1rc1__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.
Files changed (52) hide show
  1. taktiny/__init__.py +40 -0
  2. taktiny/data/__init__.py +54 -0
  3. taktiny/data/loader.py +347 -0
  4. taktiny/data/transforms.py +750 -0
  5. taktiny/nn/__init__.py +22 -0
  6. taktiny/nn/base.py +571 -0
  7. taktiny/nn/block.py +689 -0
  8. taktiny/nn/flatten.py +250 -0
  9. taktiny/nn/modules/__init__.py +23 -0
  10. taktiny/nn/modules/activation.py +282 -0
  11. taktiny/nn/modules/convolution.py +2255 -0
  12. taktiny/nn/modules/embedding.py +203 -0
  13. taktiny/nn/modules/linear.py +550 -0
  14. taktiny/nn/modules/normalization.py +1001 -0
  15. taktiny/nn/modules/peft.py +951 -0
  16. taktiny/nn/modules/recurrent.py +1717 -0
  17. taktiny/nn/modules/transformer.py +1471 -0
  18. taktiny/nn/regularization.py +498 -0
  19. taktiny/nn/resampling.py +351 -0
  20. taktiny/nn/rng.py +177 -0
  21. taktiny/nn/utils.py +649 -0
  22. taktiny/py.typed +0 -0
  23. taktiny/takt/__init__.py +36 -0
  24. taktiny/takt/adapter/__init__.py +34 -0
  25. taktiny/takt/adapter/adalora.py +51 -0
  26. taktiny/takt/adapter/base.py +111 -0
  27. taktiny/takt/adapter/dora.py +51 -0
  28. taktiny/takt/adapter/loha.py +51 -0
  29. taktiny/takt/adapter/lokr.py +51 -0
  30. taktiny/takt/adapter/lora.py +47 -0
  31. taktiny/takt/adapter/vera.py +112 -0
  32. taktiny/takt/base.py +131 -0
  33. taktiny/trainer/__init__.py +19 -0
  34. taktiny/trainer/callbacks.py +165 -0
  35. taktiny/trainer/checkpoint.py +287 -0
  36. taktiny/trainer/config.py +258 -0
  37. taktiny/trainer/evaluate.py +225 -0
  38. taktiny/trainer/trainer.py +1447 -0
  39. taktiny/utils/__init__.py +13 -0
  40. taktiny/utils/format.py +114 -0
  41. taktiny/utils/quantization.py +190 -0
  42. taktiny/utils/sharding.py +80 -0
  43. taktiny/utils/spmd.py +166 -0
  44. taktiny/utils/sync.py +32 -0
  45. taktiny/utils/trainer.py +352 -0
  46. taktiny/utils/transforms.py +209 -0
  47. taktiny/utils/typing.py +146 -0
  48. taktiny/utils/weights.py +97 -0
  49. taktiny-0.0.1rc1.dist-info/METADATA +423 -0
  50. taktiny-0.0.1rc1.dist-info/RECORD +52 -0
  51. taktiny-0.0.1rc1.dist-info/WHEEL +4 -0
  52. taktiny-0.0.1rc1.dist-info/licenses/LICENSE.md +202 -0
taktiny/__init__.py ADDED
@@ -0,0 +1,40 @@
1
+ # Copyright 2026 Shinapri
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 importlib.metadata import version
16
+
17
+ __author__ = "Shinapri"
18
+ __version__ = version('taktiny')
19
+ __description__ = (
20
+ "Build, train, and scale neural networks with JAX."
21
+ )
22
+
23
+ from taktiny import data as data
24
+ from taktiny import nn as nn
25
+ from taktiny import takt as takt
26
+ from taktiny import trainer as trainer
27
+ from taktiny import utils as utils
28
+ from taktiny.takt import Takt as Takt
29
+ from taktiny.utils.transforms import scan, vmap
30
+
31
+ __all__ = [
32
+ 'data',
33
+ 'nn',
34
+ 'takt',
35
+ 'trainer',
36
+ 'utils',
37
+ 'Takt',
38
+ 'vmap',
39
+ 'scan',
40
+ ]
@@ -0,0 +1,54 @@
1
+ # Copyright 2026 Shinapri
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
+ """Generic preprocessing for caller-provided data; no automatic downloads.
15
+
16
+ Use DataLoader with composable operations, or call Map/Compose/MapFields on
17
+ individual examples. Text-specific helpers also remain available from .text.
18
+ """
19
+
20
+ from taktiny.data.loader import DataLoader, RandomAccessSource, train_validation_split
21
+ from taktiny.data.transforms import (
22
+ ApplyTemplate,
23
+ Batch,
24
+ BatchMap,
25
+ Compose,
26
+ Filter,
27
+ FlatMap,
28
+ IndexMap,
29
+ Map,
30
+ MapFields,
31
+ Pack,
32
+ RandomMap,
33
+ )
34
+
35
+ __all__ = [
36
+ 'ApplyTemplate',
37
+ 'Batch',
38
+ 'BatchMap',
39
+ 'CausalLMBatch',
40
+ 'Compose',
41
+ 'DataLoader',
42
+ 'DatasetUtils',
43
+ 'Filter',
44
+ 'FlatMap',
45
+ 'IndexMap',
46
+ 'Map',
47
+ 'MapFields',
48
+ 'Pack',
49
+ 'PackSequences',
50
+ 'RandomAccessSource',
51
+ 'RandomMap',
52
+ 'tokenize',
53
+ 'train_validation_split'
54
+ ]
taktiny/data/loader.py ADDED
@@ -0,0 +1,347 @@
1
+ # Copyright 2026 Shinapri
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
+ """Load already-available, random-access data without prescribing a modality."""
15
+
16
+ from __future__ import annotations
17
+
18
+ import sys
19
+ from collections.abc import Callable, Mapping, Sequence
20
+ from dataclasses import replace
21
+ from typing import Any, Protocol
22
+
23
+ import grain.python as grain
24
+ import numpy as np
25
+ from absl import flags
26
+ from absl.flags import UnparsedFlagAccessError
27
+ from grain._src.python.dataset import base as dataset_base
28
+
29
+ from taktiny.data.transforms import Batch, _expand_operations
30
+
31
+
32
+ class RandomAccessSource(Protocol):
33
+ """Structural interface for finite sources; no framework inheritance needed."""
34
+
35
+ def __len__(self) -> int: ...
36
+
37
+ def __getitem__(self, index: int, /) -> Any: ...
38
+
39
+
40
+ class _ShardSampler:
41
+ """Present a shard as a local sampler, including uneven and empty tails.
42
+
43
+ Grain 0.2.18 DataLoader floors sampler length / shard_count even when
44
+ drop_remainder=False. Do the partitioning here and disable its second
45
+ partitioning step. Keep global RNGs but expose local traversal indices.
46
+ """
47
+
48
+ def __init__(
49
+ self, sampler: grain.IndexSampler | None,
50
+ shard_index: int, shard_count: int,
51
+ ) -> None:
52
+ self.sampler = sampler
53
+ self.shard_index = shard_index
54
+ self.shard_count = shard_count
55
+ self._shard_options = grain.NoSharding()
56
+
57
+ def __len__(self) -> int:
58
+ size = len(self.sampler) if self.sampler is not None else 0
59
+ if size == sys.maxsize:
60
+ return sys.maxsize
61
+ return max(0, (size - self.shard_index + self.shard_count - 1) // self.shard_count)
62
+
63
+ def __getitem__(self, index: int) -> grain.RecordMetadata:
64
+ if index < 0 or index >= len(self) or self.sampler is None:
65
+ raise IndexError(index)
66
+ record = self.sampler[index * self.shard_count + self.shard_index]
67
+ return replace(record, index=index)
68
+
69
+ def __repr__(self) -> str:
70
+ return (f'_ShardSampler({self.sampler!r}, shard_index={self.shard_index}, '
71
+ f'shard_count={self.shard_count})')
72
+
73
+
74
+ def _prepare_grain_workers() -> None:
75
+ """Allow Grain workers to start when Abseil flags are still unparsed."""
76
+ if flags.FLAGS.is_parsed():
77
+ return
78
+
79
+ # Grain 0.2.18 reads this FlagHolder while constructing its worker pool.
80
+ # Reading a holder before absl.app.run() raises in notebooks and regular
81
+ # Python programs. The underlying Flag exposes the same live value without
82
+ # requiring TakTiny to parse the application's complete flag registry.
83
+ from grain._src.core import profiler
84
+
85
+ name = '_GRAIN_ENABLE_MULTIPROCESS_WORKER_PROFILING'
86
+ holder = getattr(profiler, name, None)
87
+ if holder is None:
88
+ return
89
+ try:
90
+ holder.value # noqa: B018
91
+ except UnparsedFlagAccessError:
92
+ setattr(profiler, name, flags.FLAGS[holder.name])
93
+
94
+
95
+ class DataLoader(grain.DataLoader):
96
+ """Preprocess and iterate over caller-provided, random-access records.
97
+
98
+ Records may be arrays, mappings, tuples, images, audio, strings, or custom
99
+ objects. The source is never downloaded, decoded, or copied into memory.
100
+ Supply a list, array, already-loaded dataset, or an object implementing
101
+ __len__ and integer __getitem__. This loader does not accept streaming
102
+ generators; use a streaming backend directly, or explicitly materialize a
103
+ finite stream with list(source) if it fits in memory.
104
+
105
+ Args:
106
+ source: Caller-owned random-access data, not a repository ID or path.
107
+ operations: Ordered Taktiny or native Grain operations. Use Map for a
108
+ record callable, RandomMap for augmentation, and Filter to drop
109
+ records. Operations are lazy and run when the loader is iterated.
110
+ batch_size: Optional final batch size, applied after all operations.
111
+ None emits records unchanged. For operations after batching, put
112
+ Batch directly in operations and leave this argument unset.
113
+ drop_remainder: Drop an incomplete final batch; requires batch_size.
114
+ collate_fn: Optional function(rows) for final batching. None uses Grain
115
+ stacking; list preserves ragged or custom objects without padding.
116
+ Requires batch_size. Collation runs independently in each worker.
117
+ sampler: Optional native Grain sampler. When provided, it owns sampling,
118
+ epochs, seed, and sharding; the corresponding convenience arguments
119
+ are ignored after validation.
120
+ shuffle: Shuffle indices using seed; defaults to False.
121
+ seed: Unsigned 32-bit integer seed for sampling and RandomMap augmentation.
122
+ num_epochs: Positive epoch count (default 1); None repeats indefinitely.
123
+ Each new iterator starts from the beginning unless state is restored.
124
+ shard_index: This process's data shard, in [0, shard_count).
125
+ shard_count: Number of data shards. Shards may have unequal lengths;
126
+ this is input partitioning, not JAX device-array sharding.
127
+ worker_count: Child workers; 0 runs locally, None lets Grain choose.
128
+ Sources and transforms must be serializable when workers are used.
129
+ worker_buffer_size: Positive per-worker prefetch buffer size.
130
+
131
+ Iterators retain Grain's get_state()/set_state() checkpoint API. Restore
132
+ against the same source and pipeline. Custom iterator operations retain
133
+ their own Grain checkpoint limitations. Transforms should be deterministic
134
+ apart from RandomMap's supplied RNG and should not mutate source records.
135
+
136
+ Example:
137
+ >>> from taktiny.data import DataLoader, MapFields
138
+ >>> rows = [{'value': 255, 'label': 0}, {'value': 0, 'label': 1}]
139
+ >>> loader = DataLoader(rows, operations=[
140
+ ... MapFields({'value': lambda x: x / 255})], batch_size=2)
141
+ >>> next(iter(loader))['value'].tolist()
142
+ [1.0, 0.0]
143
+ """
144
+ def __init__(
145
+ self,
146
+ source: dataset_base.RandomAccessDataSource | Any,
147
+ *,
148
+ operations: Sequence[Any] = (),
149
+ batch_size: int | None = None,
150
+ drop_remainder: bool = False,
151
+ collate_fn: Callable[[Sequence[Any]], Any] | None = None,
152
+ sampler: grain.Sampler | None = None,
153
+ shuffle: bool = False,
154
+ seed: int = 0,
155
+ num_epochs: int | None = 1,
156
+ shard_index: int = 0,
157
+ shard_count: int = 1,
158
+ worker_count: int | None = 0,
159
+ worker_buffer_size: int = 1,
160
+ ) -> None:
161
+ """Create a Grain loader from a random-access dataset.
162
+
163
+ ``operations`` are applied exactly in the supplied order. Mapping,
164
+ filtering, packing, batching, and collation therefore remain separate
165
+ concerns and can be composed using Grain transformations or custom
166
+ Grain operations.
167
+
168
+ When ``sampler`` is omitted, an :class:`grain.IndexSampler` is created
169
+ from the remaining sampling arguments. Supplying ``sampler`` transfers
170
+ sampling and sharding responsibility entirely to that object. The
171
+ default ``num_epochs=1`` creates a single-epoch (finite) loader; pass
172
+ ``None`` for an unbounded loader.
173
+ """
174
+ _validate_source(source)
175
+
176
+ if operations is None or isinstance(operations, (str, bytes)):
177
+ raise TypeError('operations must be a sequence')
178
+
179
+ try:
180
+ operations = tuple(operations)
181
+ except TypeError as error:
182
+ raise TypeError('operations must be a sequence') from error
183
+
184
+ operations = _expand_operations(operations)
185
+ if not isinstance(drop_remainder, bool):
186
+ raise TypeError('drop_remainder must be a boolean')
187
+
188
+ if batch_size is None:
189
+ if drop_remainder or collate_fn is not None:
190
+ raise ValueError('drop_remainder and collate_fn require batch_size')
191
+ else:
192
+ operations += (Batch(batch_size, drop_remainder=drop_remainder,
193
+ collate_fn=collate_fn),)
194
+
195
+ if not isinstance(shuffle, bool):
196
+ raise TypeError('shuffle must be a boolean')
197
+
198
+ if isinstance(seed, bool) or not isinstance(seed, int):
199
+ raise TypeError('seed must be an integer')
200
+
201
+ if not 0 <= seed < 2**32:
202
+ raise ValueError('seed must be an unsigned 32-bit integer')
203
+
204
+ if (
205
+ num_epochs is not None
206
+ and (
207
+ isinstance(num_epochs, bool)
208
+ or not isinstance(num_epochs, int)
209
+ or num_epochs < 1
210
+ )
211
+ ):
212
+ raise ValueError('num_epochs must be a positive integer or None')
213
+
214
+ if (
215
+ isinstance(shard_count, bool)
216
+ or not isinstance(shard_count, int)
217
+ or shard_count < 1
218
+ ):
219
+ raise ValueError('shard_count must be a positive integer')
220
+
221
+ if (
222
+ isinstance(shard_index, bool)
223
+ or not isinstance(shard_index, int)
224
+ or not 0 <= shard_index < shard_count
225
+ ):
226
+ raise ValueError(
227
+ 'shard_index must be between zero and shard_count - 1'
228
+ )
229
+
230
+ if (
231
+ worker_count is not None
232
+ and (
233
+ isinstance(worker_count, bool)
234
+ or not isinstance(worker_count, int)
235
+ or worker_count < 0
236
+ )
237
+ ):
238
+ raise ValueError('worker_count must be non-negative or None')
239
+
240
+ if (
241
+ isinstance(worker_buffer_size, bool)
242
+ or not isinstance(worker_buffer_size, int)
243
+ or worker_buffer_size < 1
244
+ ):
245
+ raise ValueError('worker_buffer_size must be a positive integer')
246
+
247
+ if sampler is None:
248
+ try:
249
+ num_records = len(source)
250
+ except TypeError as error:
251
+ raise TypeError(
252
+ 'source must have a finite length when sampler is omitted'
253
+ ) from error
254
+
255
+ base_sampler = grain.IndexSampler(
256
+ num_records=num_records,
257
+ num_epochs=num_epochs,
258
+ shard_options=grain.NoSharding(),
259
+ shuffle=shuffle,
260
+ seed=seed,
261
+ ) if num_records else None
262
+ sampler = _ShardSampler(base_sampler, shard_index, shard_count)
263
+
264
+ if worker_count is None or worker_count > 0:
265
+ _prepare_grain_workers()
266
+
267
+ super().__init__(
268
+ data_source=source,
269
+ sampler=sampler,
270
+ operations=operations,
271
+ worker_count=worker_count,
272
+ worker_buffer_size=worker_buffer_size,
273
+ )
274
+
275
+
276
+
277
+ def _validate_source(source: Any) -> None:
278
+ if isinstance(source, (str, bytes, Mapping)):
279
+ raise TypeError('source must contain records, not a path, repository ID, or column mapping')
280
+ if not hasattr(source, '__getitem__'):
281
+ raise TypeError('source must support random access; materialize finite iterables explicitly')
282
+
283
+
284
+ def train_validation_split(
285
+ source: RandomAccessSource,
286
+ validation_size: float,
287
+ *,
288
+ shuffle: bool = True,
289
+ seed: int = 0,
290
+ ) -> tuple[Any, Any]:
291
+ """Split a random-access source into ``(train, validation)`` views.
292
+
293
+ ``validation_size`` may be a count (``int``) or a fraction (``float``
294
+ in ``(0, 1)``). The returned views are random-access and can be passed
295
+ directly to DataLoader. Fractions are rounded to the nearest integer;
296
+ both splits must be nonempty. The source itself is not copied or shuffled.
297
+ """
298
+ _validate_source(source)
299
+ if not isinstance(shuffle, bool):
300
+ raise TypeError('shuffle must be a boolean')
301
+ if isinstance(seed, bool) or not isinstance(seed, int):
302
+ raise TypeError('seed must be an integer')
303
+
304
+ count = len(source)
305
+ if isinstance(validation_size, bool):
306
+ raise TypeError('validation_size must be an int or float')
307
+ if isinstance(validation_size, float):
308
+ if not 0.0 < validation_size < 1.0:
309
+ raise ValueError('float validation_size must be in (0, 1)')
310
+ validation_count = round(count * validation_size)
311
+ elif isinstance(validation_size, int):
312
+ if not 0 < validation_size < count:
313
+ raise ValueError(
314
+ f'int validation_size must be in (0, {count})'
315
+ )
316
+ validation_count = validation_size
317
+ else:
318
+ raise TypeError('validation_size must be an int or float')
319
+
320
+ if not 0 < validation_count < count:
321
+ raise ValueError('validation_size must leave both splits nonempty')
322
+
323
+ indices = np.arange(count)
324
+ if shuffle:
325
+ indices = np.random.default_rng(seed).permutation(count)
326
+ train = _IndexedView(source, indices[validation_count:])
327
+ validation = _IndexedView(source, indices[:validation_count])
328
+ return train, validation
329
+
330
+
331
+ class _IndexedView:
332
+ """Random-access view over a subset of a source's indices."""
333
+
334
+ def __init__(self, source: RandomAccessSource, indices: np.ndarray) -> None:
335
+ self._source = source
336
+ self._indices = indices
337
+
338
+ def __len__(self) -> int:
339
+ return len(self._indices)
340
+
341
+ def __getitem__(self, index: int | slice) -> Any:
342
+ if isinstance(index, slice):
343
+ return _IndexedView(self._source, self._indices[index])
344
+ return self._source[int(self._indices[index])]
345
+
346
+
347
+ __all__ = ['DataLoader', 'RandomAccessSource', 'train_validation_split']