keras-rs 0.2.1.dev0__tar.gz → 0.3.0.dev0__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (61) hide show
  1. {keras_rs-0.2.1.dev0 → keras_rs-0.3.0.dev0}/PKG-INFO +4 -3
  2. {keras_rs-0.2.1.dev0 → keras_rs-0.3.0.dev0}/keras_rs/src/layers/embedding/base_distributed_embedding.py +88 -60
  3. {keras_rs-0.2.1.dev0 → keras_rs-0.3.0.dev0}/keras_rs/src/layers/embedding/distributed_embedding_config.py +6 -3
  4. keras_rs-0.3.0.dev0/keras_rs/src/layers/embedding/jax/checkpoint_utils.py +104 -0
  5. {keras_rs-0.2.1.dev0 → keras_rs-0.3.0.dev0}/keras_rs/src/layers/embedding/jax/config_conversion.py +75 -5
  6. {keras_rs-0.2.1.dev0 → keras_rs-0.3.0.dev0}/keras_rs/src/layers/embedding/jax/distributed_embedding.py +55 -181
  7. {keras_rs-0.2.1.dev0 → keras_rs-0.3.0.dev0}/keras_rs/src/layers/embedding/jax/embedding_lookup.py +2 -2
  8. {keras_rs-0.2.1.dev0 → keras_rs-0.3.0.dev0}/keras_rs/src/layers/embedding/jax/embedding_utils.py +68 -22
  9. {keras_rs-0.2.1.dev0 → keras_rs-0.3.0.dev0}/keras_rs/src/layers/embedding/tensorflow/config_conversion.py +62 -22
  10. {keras_rs-0.2.1.dev0 → keras_rs-0.3.0.dev0}/keras_rs/src/layers/embedding/tensorflow/distributed_embedding.py +18 -6
  11. {keras_rs-0.2.1.dev0 → keras_rs-0.3.0.dev0}/keras_rs/src/version.py +1 -1
  12. {keras_rs-0.2.1.dev0 → keras_rs-0.3.0.dev0}/keras_rs.egg-info/PKG-INFO +4 -3
  13. {keras_rs-0.2.1.dev0 → keras_rs-0.3.0.dev0}/keras_rs.egg-info/SOURCES.txt +1 -0
  14. {keras_rs-0.2.1.dev0 → keras_rs-0.3.0.dev0}/pyproject.toml +3 -2
  15. {keras_rs-0.2.1.dev0 → keras_rs-0.3.0.dev0}/README.md +0 -0
  16. {keras_rs-0.2.1.dev0 → keras_rs-0.3.0.dev0}/keras_rs/api/__init__.py +0 -0
  17. {keras_rs-0.2.1.dev0 → keras_rs-0.3.0.dev0}/keras_rs/api/layers/__init__.py +0 -0
  18. {keras_rs-0.2.1.dev0 → keras_rs-0.3.0.dev0}/keras_rs/api/losses/__init__.py +0 -0
  19. {keras_rs-0.2.1.dev0 → keras_rs-0.3.0.dev0}/keras_rs/api/metrics/__init__.py +0 -0
  20. {keras_rs-0.2.1.dev0 → keras_rs-0.3.0.dev0}/keras_rs/src/__init__.py +0 -0
  21. {keras_rs-0.2.1.dev0 → keras_rs-0.3.0.dev0}/keras_rs/src/api_export.py +0 -0
  22. {keras_rs-0.2.1.dev0 → keras_rs-0.3.0.dev0}/keras_rs/src/layers/__init__.py +0 -0
  23. {keras_rs-0.2.1.dev0 → keras_rs-0.3.0.dev0}/keras_rs/src/layers/embedding/__init__.py +0 -0
  24. {keras_rs-0.2.1.dev0 → keras_rs-0.3.0.dev0}/keras_rs/src/layers/embedding/distributed_embedding.py +0 -0
  25. {keras_rs-0.2.1.dev0 → keras_rs-0.3.0.dev0}/keras_rs/src/layers/embedding/embed_reduce.py +0 -0
  26. {keras_rs-0.2.1.dev0 → keras_rs-0.3.0.dev0}/keras_rs/src/layers/embedding/jax/__init__.py +0 -0
  27. {keras_rs-0.2.1.dev0 → keras_rs-0.3.0.dev0}/keras_rs/src/layers/embedding/tensorflow/__init__.py +0 -0
  28. {keras_rs-0.2.1.dev0 → keras_rs-0.3.0.dev0}/keras_rs/src/layers/feature_interaction/__init__.py +0 -0
  29. {keras_rs-0.2.1.dev0 → keras_rs-0.3.0.dev0}/keras_rs/src/layers/feature_interaction/dot_interaction.py +0 -0
  30. {keras_rs-0.2.1.dev0 → keras_rs-0.3.0.dev0}/keras_rs/src/layers/feature_interaction/feature_cross.py +0 -0
  31. {keras_rs-0.2.1.dev0 → keras_rs-0.3.0.dev0}/keras_rs/src/layers/retrieval/__init__.py +0 -0
  32. {keras_rs-0.2.1.dev0 → keras_rs-0.3.0.dev0}/keras_rs/src/layers/retrieval/brute_force_retrieval.py +0 -0
  33. {keras_rs-0.2.1.dev0 → keras_rs-0.3.0.dev0}/keras_rs/src/layers/retrieval/hard_negative_mining.py +0 -0
  34. {keras_rs-0.2.1.dev0 → keras_rs-0.3.0.dev0}/keras_rs/src/layers/retrieval/remove_accidental_hits.py +0 -0
  35. {keras_rs-0.2.1.dev0 → keras_rs-0.3.0.dev0}/keras_rs/src/layers/retrieval/retrieval.py +0 -0
  36. {keras_rs-0.2.1.dev0 → keras_rs-0.3.0.dev0}/keras_rs/src/layers/retrieval/sampling_probability_correction.py +0 -0
  37. {keras_rs-0.2.1.dev0 → keras_rs-0.3.0.dev0}/keras_rs/src/losses/__init__.py +0 -0
  38. {keras_rs-0.2.1.dev0 → keras_rs-0.3.0.dev0}/keras_rs/src/losses/pairwise_hinge_loss.py +0 -0
  39. {keras_rs-0.2.1.dev0 → keras_rs-0.3.0.dev0}/keras_rs/src/losses/pairwise_logistic_loss.py +0 -0
  40. {keras_rs-0.2.1.dev0 → keras_rs-0.3.0.dev0}/keras_rs/src/losses/pairwise_loss.py +0 -0
  41. {keras_rs-0.2.1.dev0 → keras_rs-0.3.0.dev0}/keras_rs/src/losses/pairwise_loss_utils.py +0 -0
  42. {keras_rs-0.2.1.dev0 → keras_rs-0.3.0.dev0}/keras_rs/src/losses/pairwise_mean_squared_error.py +0 -0
  43. {keras_rs-0.2.1.dev0 → keras_rs-0.3.0.dev0}/keras_rs/src/losses/pairwise_soft_zero_one_loss.py +0 -0
  44. {keras_rs-0.2.1.dev0 → keras_rs-0.3.0.dev0}/keras_rs/src/metrics/__init__.py +0 -0
  45. {keras_rs-0.2.1.dev0 → keras_rs-0.3.0.dev0}/keras_rs/src/metrics/dcg.py +0 -0
  46. {keras_rs-0.2.1.dev0 → keras_rs-0.3.0.dev0}/keras_rs/src/metrics/mean_average_precision.py +0 -0
  47. {keras_rs-0.2.1.dev0 → keras_rs-0.3.0.dev0}/keras_rs/src/metrics/mean_reciprocal_rank.py +0 -0
  48. {keras_rs-0.2.1.dev0 → keras_rs-0.3.0.dev0}/keras_rs/src/metrics/ndcg.py +0 -0
  49. {keras_rs-0.2.1.dev0 → keras_rs-0.3.0.dev0}/keras_rs/src/metrics/precision_at_k.py +0 -0
  50. {keras_rs-0.2.1.dev0 → keras_rs-0.3.0.dev0}/keras_rs/src/metrics/ranking_metric.py +0 -0
  51. {keras_rs-0.2.1.dev0 → keras_rs-0.3.0.dev0}/keras_rs/src/metrics/ranking_metrics_utils.py +0 -0
  52. {keras_rs-0.2.1.dev0 → keras_rs-0.3.0.dev0}/keras_rs/src/metrics/recall_at_k.py +0 -0
  53. {keras_rs-0.2.1.dev0 → keras_rs-0.3.0.dev0}/keras_rs/src/metrics/utils.py +0 -0
  54. {keras_rs-0.2.1.dev0 → keras_rs-0.3.0.dev0}/keras_rs/src/types.py +0 -0
  55. {keras_rs-0.2.1.dev0 → keras_rs-0.3.0.dev0}/keras_rs/src/utils/__init__.py +0 -0
  56. {keras_rs-0.2.1.dev0 → keras_rs-0.3.0.dev0}/keras_rs/src/utils/doc_string_utils.py +0 -0
  57. {keras_rs-0.2.1.dev0 → keras_rs-0.3.0.dev0}/keras_rs/src/utils/keras_utils.py +0 -0
  58. {keras_rs-0.2.1.dev0 → keras_rs-0.3.0.dev0}/keras_rs.egg-info/dependency_links.txt +0 -0
  59. {keras_rs-0.2.1.dev0 → keras_rs-0.3.0.dev0}/keras_rs.egg-info/requires.txt +0 -0
  60. {keras_rs-0.2.1.dev0 → keras_rs-0.3.0.dev0}/keras_rs.egg-info/top_level.txt +0 -0
  61. {keras_rs-0.2.1.dev0 → keras_rs-0.3.0.dev0}/setup.cfg +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: keras-rs
3
- Version: 0.2.1.dev0
3
+ Version: 0.3.0.dev0
4
4
  Summary: Multi-backend recommender systems with Keras 3.
5
5
  Author-email: Keras team <keras-users@googlegroups.com>
6
6
  License: Apache License 2.0
@@ -8,8 +8,9 @@ Project-URL: Home, https://keras.io/keras_rs
8
8
  Project-URL: Repository, https://github.com/keras-team/keras-rs
9
9
  Classifier: Development Status :: 3 - Alpha
10
10
  Classifier: Programming Language :: Python :: 3
11
- Classifier: Programming Language :: Python :: 3.10
12
11
  Classifier: Programming Language :: Python :: 3.11
12
+ Classifier: Programming Language :: Python :: 3.12
13
+ Classifier: Programming Language :: Python :: 3.13
13
14
  Classifier: Programming Language :: Python :: 3 :: Only
14
15
  Classifier: Operating System :: Unix
15
16
  Classifier: Operating System :: Microsoft :: Windows
@@ -17,7 +18,7 @@ Classifier: Operating System :: MacOS
17
18
  Classifier: Intended Audience :: Science/Research
18
19
  Classifier: Topic :: Scientific/Engineering
19
20
  Classifier: Topic :: Software Development
20
- Requires-Python: >=3.10
21
+ Requires-Python: >=3.11
21
22
  Description-Content-Type: text/markdown
22
23
  Requires-Dist: keras
23
24
  Requires-Dist: ml-dtypes
@@ -1,4 +1,5 @@
1
1
  import collections
2
+ import dataclasses
2
3
  import importlib.util
3
4
  import typing
4
5
  from typing import Any, Sequence
@@ -20,9 +21,10 @@ EmbedReduce = embed_reduce.EmbedReduce
20
21
  SUPPORTED_PLACEMENTS = ("auto", "default_device", "sparsecore")
21
22
 
22
23
 
23
- PlacementAndPath = collections.namedtuple(
24
- "PlacementAndPath", ["placement", "path"]
25
- )
24
+ @dataclasses.dataclass(eq=True, unsafe_hash=True, order=True)
25
+ class PlacementAndPath:
26
+ placement: str
27
+ path: str
26
28
 
27
29
 
28
30
  def _ragged_to_dense_inputs(
@@ -146,14 +148,14 @@ class DistributedEmbedding(keras.layers.Layer):
146
148
  feature1 = keras_rs.layers.FeatureConfig(
147
149
  name="feature1",
148
150
  table=table1,
149
- input_shape=(PER_REPLICA_BATCH_SIZE,),
150
- output_shape=(PER_REPLICA_BATCH_SIZE, TABLE1_EMBEDDING_SIZE),
151
+ input_shape=(GLOBAL_BATCH_SIZE,),
152
+ output_shape=(GLOBAL_BATCH_SIZE, TABLE1_EMBEDDING_SIZE),
151
153
  )
152
154
  feature2 = keras_rs.layers.FeatureConfig(
153
155
  name="feature2",
154
156
  table=table2,
155
- input_shape=(PER_REPLICA_BATCH_SIZE,),
156
- output_shape=(PER_REPLICA_BATCH_SIZE, TABLE2_EMBEDDING_SIZE),
157
+ input_shape=(GLOBAL_BATCH_SIZE,),
158
+ output_shape=(GLOBAL_BATCH_SIZE, TABLE2_EMBEDDING_SIZE),
157
159
  )
158
160
 
159
161
  feature_configs = {
@@ -174,12 +176,9 @@ class DistributedEmbedding(keras.layers.Layer):
174
176
  supported on all backends and accelerators:
175
177
 
176
178
  - `keras.optimizers.Adagrad`
177
- - `keras.optimizers.SGD`
178
-
179
- The following are additionally available when using the TensorFlow backend:
180
-
181
179
  - `keras.optimizers.Adam`
182
180
  - `keras.optimizers.Ftrl`
181
+ - `keras.optimizers.SGD`
183
182
 
184
183
  Also, not all parameters of the optimizers are supported (e.g. the
185
184
  `nesterov` option of `SGD`). An error is raised when an unsupported
@@ -297,6 +296,7 @@ class DistributedEmbedding(keras.layers.Layer):
297
296
  result = strategy.run(step, args=(next(iterator),))
298
297
 
299
298
  run_loop(iter(dataset))
299
+ ```
300
300
 
301
301
  ### Usage with JAX on TPU with SpareCore
302
302
 
@@ -304,7 +304,7 @@ class DistributedEmbedding(keras.layers.Layer):
304
304
 
305
305
  To use `DistributedEmbedding` on TPUs with JAX, one must create and set a
306
306
  Keras `Distribution`.
307
- ```
307
+ ```python
308
308
  distribution = keras.distribution.DataParallel(devices=jax.device("tpu"))
309
309
  keras.distribution.set_distribution(distribution)
310
310
  ```
@@ -339,18 +339,33 @@ class DistributedEmbedding(keras.layers.Layer):
339
339
  embedding_layer = DistributedEmbedding(feature_configs)
340
340
 
341
341
  # Add preprocessing to a data input pipeline.
342
- def train_dataset_generator():
343
- for (inputs, weights), labels in iter(train_dataset):
342
+ def preprocessed_dataset_generator(dataset):
343
+ for (inputs, weights), labels in iter(dataset):
344
344
  yield embedding_layer.preprocess(
345
345
  inputs, weights, training=True
346
346
  ), labels
347
347
 
348
- preprocessed_train_dataset = train_dataset_generator()
348
+ preprocessed_train_dataset = preprocessed_dataset_generator(train_dataset)
349
349
  ```
350
350
  This explicit preprocessing stage combines the input and optional weights,
351
351
  so the new data can be passed directly into the `inputs` argument of the
352
352
  layer or model.
353
353
 
354
+ **NOTE**: When working in a multi-host setting with data parallelism, the
355
+ data needs to be sharded properly across hosts. If the original dataset is
356
+ of type `tf.data.Dataset`, it will need to be manually sharded _prior_ to
357
+ applying the preprocess generator:
358
+ ```python
359
+ # Manually shard the dataset across hosts.
360
+ train_dataset = distribution.distribute_dataset(train_dataset)
361
+ distribution.auto_shard_dataset = False # Dataset is already sharded.
362
+
363
+ # Add a preprocessing stage to the distributed data input pipeline.
364
+ train_dataset = preprocessed_dataset_generator(train_dataset)
365
+ ```
366
+ If the original dataset is _not_ a `tf.data.Dataset`, it must already be
367
+ pre-sharded across hosts.
368
+
354
369
  #### Usage in a Keras model
355
370
 
356
371
  Once the global distribution is set and the input preprocessing pipeline
@@ -505,12 +520,12 @@ class DistributedEmbedding(keras.layers.Layer):
505
520
  With these structures in place, the steps to:
506
521
  - go from the deeply nested structure to the two-level structure are:
507
522
  - `assert_same_struct` as `self._feature_configs`
508
- - `flatten`
509
- - `pack_sequence_as` `self._placement_to_path_to_feature_config`
523
+ - use `self._feature_deeply_nested_placement_and_paths` to map from
524
+ deeply nested to two-level
510
525
  - go from the two-level structure to the deeply nested structure:
511
- - `assert_same_struct` as `self._placement_to_path_to_feature_config`
512
- - `flatten`
513
- - `pack_sequence_as` `self._feature_configs`
526
+ - `assert_same_struct` as `self._placement_to_path_to_feature_config`
527
+ - use `self._feature_deeply_nested_placement_and_paths` to locate each
528
+ output in the two-level dicts
514
529
 
515
530
  Args:
516
531
  feature_configs: The deeply nested structure of `FeatureConfig` or
@@ -577,14 +592,14 @@ class DistributedEmbedding(keras.layers.Layer):
577
592
  ] = collections.defaultdict(dict)
578
593
 
579
594
  def populate_placement_to_path_to_input_shape(
580
- placement_and_path: PlacementAndPath, input_shape: types.Shape
595
+ pp: PlacementAndPath, input_shape: types.Shape
581
596
  ) -> None:
582
- placement_to_path_to_input_shape[placement_and_path.placement][
583
- placement_and_path.path
584
- ] = input_shape
597
+ placement_to_path_to_input_shape[pp.placement][pp.path] = (
598
+ input_shape
599
+ )
585
600
 
586
601
  keras.tree.map_structure_up_to(
587
- self._feature_configs,
602
+ self._feature_deeply_nested_placement_and_paths,
588
603
  populate_placement_to_path_to_input_shape,
589
604
  self._feature_deeply_nested_placement_and_paths,
590
605
  input_shapes,
@@ -632,35 +647,40 @@ class DistributedEmbedding(keras.layers.Layer):
632
647
  """
633
648
  # Verify input structure.
634
649
  keras.tree.assert_same_structure(self._feature_configs, inputs)
650
+ if weights is not None:
651
+ keras.tree.assert_same_structure(self._feature_configs, weights)
635
652
 
636
653
  if not self.built:
637
- input_shapes = keras.tree.map_structure_up_to(
638
- self._feature_configs,
654
+ input_shapes = keras.tree.map_structure(
639
655
  lambda array: backend.standardize_shape(array.shape),
640
656
  inputs,
641
657
  )
642
658
  self.build(input_shapes)
643
659
 
644
- # Go from deeply nested structure of inputs to flat inputs.
645
- flat_inputs = keras.tree.flatten(inputs)
660
+ # Go from deeply nested to nested dict placement -> path -> input.
661
+ def to_placement_to_path(
662
+ tensors: types.Nested[types.Tensor],
663
+ ) -> dict[str, dict[str, types.Tensor]]:
664
+ result: dict[str, dict[str, types.Tensor]] = {
665
+ p: dict() for p in self._placement_to_path_to_feature_config
666
+ }
646
667
 
647
- # Go from flat to nested dict placement -> path -> input.
648
- placement_to_path_to_inputs = keras.tree.pack_sequence_as(
649
- self._placement_to_path_to_feature_config, flat_inputs
650
- )
668
+ def populate(pp: PlacementAndPath, x: types.Tensor) -> None:
669
+ result[pp.placement][pp.path] = x
651
670
 
652
- if weights is not None:
653
- # Same for weights if present.
654
- keras.tree.assert_same_structure(self._feature_configs, weights)
655
- flat_weights = keras.tree.flatten(weights)
656
- placement_to_path_to_weights = keras.tree.pack_sequence_as(
657
- self._placement_to_path_to_feature_config, flat_weights
671
+ keras.tree.map_structure(
672
+ populate,
673
+ self._feature_deeply_nested_placement_and_paths,
674
+ tensors,
658
675
  )
659
- else:
660
- # Populate keys for weights.
661
- placement_to_path_to_weights = {
662
- k: None for k in placement_to_path_to_inputs
663
- }
676
+ return result
677
+
678
+ placement_to_path_to_inputs = to_placement_to_path(inputs)
679
+
680
+ # Same for weights if present.
681
+ placement_to_path_to_weights = (
682
+ to_placement_to_path(weights) if weights is not None else None
683
+ )
664
684
 
665
685
  placement_to_path_to_preprocessed: dict[
666
686
  str, dict[str, dict[str, types.Nested[types.Tensor]]]
@@ -671,7 +691,9 @@ class DistributedEmbedding(keras.layers.Layer):
671
691
  placement_to_path_to_preprocessed["sparsecore"] = (
672
692
  self._sparsecore_preprocess(
673
693
  placement_to_path_to_inputs["sparsecore"],
674
- placement_to_path_to_weights["sparsecore"],
694
+ placement_to_path_to_weights["sparsecore"]
695
+ if placement_to_path_to_weights is not None
696
+ else None,
675
697
  training,
676
698
  )
677
699
  )
@@ -681,7 +703,9 @@ class DistributedEmbedding(keras.layers.Layer):
681
703
  placement_to_path_to_preprocessed["default_device"] = (
682
704
  self._default_device_preprocess(
683
705
  placement_to_path_to_inputs["default_device"],
684
- placement_to_path_to_weights["default_device"],
706
+ placement_to_path_to_weights["default_device"]
707
+ if placement_to_path_to_weights is not None
708
+ else None,
685
709
  training,
686
710
  )
687
711
  )
@@ -767,11 +791,13 @@ class DistributedEmbedding(keras.layers.Layer):
767
791
  placement_to_path_to_outputs,
768
792
  )
769
793
 
770
- # Go from placement -> path -> output to flat outputs.
771
- flat_outputs = keras.tree.flatten(placement_to_path_to_outputs)
794
+ # Go from placement -> path -> output to deeply nested structure.
795
+ def populate_output(pp: PlacementAndPath) -> types.Tensor:
796
+ return placement_to_path_to_outputs[pp.placement][pp.path]
772
797
 
773
- # Go from flat outputs to deeply nested structure.
774
- return keras.tree.pack_sequence_as(self._feature_configs, flat_outputs)
798
+ return keras.tree.map_structure(
799
+ populate_output, self._feature_deeply_nested_placement_and_paths
800
+ )
775
801
 
776
802
  def get_embedding_tables(self) -> dict[str, types.Tensor]:
777
803
  """Return the content of the embedding tables by table name.
@@ -796,13 +822,13 @@ class DistributedEmbedding(keras.layers.Layer):
796
822
  table_stacking: str | Sequence[Sequence[str]],
797
823
  ) -> None:
798
824
  del table_stacking
799
- table_to_embedding_layer: dict[TableConfig, EmbedReduce] = {}
825
+ table_config_id_to_embedding_layer: dict[int, EmbedReduce] = {}
800
826
  self._default_device_embedding_layers: dict[str, EmbedReduce] = {}
801
827
 
802
828
  for path, feature_config in feature_configs.items():
803
- if feature_config.table in table_to_embedding_layer:
829
+ if id(feature_config.table) in table_config_id_to_embedding_layer:
804
830
  self._default_device_embedding_layers[path] = (
805
- table_to_embedding_layer[feature_config.table]
831
+ table_config_id_to_embedding_layer[id(feature_config.table)]
806
832
  )
807
833
  else:
808
834
  embedding_layer = EmbedReduce(
@@ -812,7 +838,9 @@ class DistributedEmbedding(keras.layers.Layer):
812
838
  embeddings_initializer=feature_config.table.initializer,
813
839
  combiner=feature_config.table.combiner,
814
840
  )
815
- table_to_embedding_layer[feature_config.table] = embedding_layer
841
+ table_config_id_to_embedding_layer[id(feature_config.table)] = (
842
+ embedding_layer
843
+ )
816
844
  self._default_device_embedding_layers[path] = embedding_layer
817
845
 
818
846
  def _default_device_build(
@@ -987,8 +1015,8 @@ class DistributedEmbedding(keras.layers.Layer):
987
1015
 
988
1016
  # The serialized `TableConfig` objects.
989
1017
  table_config_dicts: list[dict[str, Any]] = []
990
- # Mapping from `TableConfig` to index in `table_config_dicts`.
991
- table_config_indices: dict[TableConfig, int] = {}
1018
+ # Mapping from `TableConfig` id to index in `table_config_dicts`.
1019
+ table_config_id_to_index: dict[int, int] = {}
992
1020
 
993
1021
  def serialize_feature_config(
994
1022
  feature_config: FeatureConfig,
@@ -998,17 +1026,17 @@ class DistributedEmbedding(keras.layers.Layer):
998
1026
  # key.
999
1027
  feature_config_dict = feature_config.get_config()
1000
1028
 
1001
- if feature_config.table not in table_config_indices:
1029
+ if id(feature_config.table) not in table_config_id_to_index:
1002
1030
  # Save the serialized `TableConfig` the first time we see it and
1003
1031
  # remember its index.
1004
- table_config_indices[feature_config.table] = len(
1032
+ table_config_id_to_index[id(feature_config.table)] = len(
1005
1033
  table_config_dicts
1006
1034
  )
1007
1035
  table_config_dicts.append(feature_config_dict["table"])
1008
1036
 
1009
1037
  # Replace the serialized `TableConfig` with its index.
1010
- feature_config_dict["table"] = table_config_indices[
1011
- feature_config.table
1038
+ feature_config_dict["table"] = table_config_id_to_index[
1039
+ id(feature_config.table)
1012
1040
  ]
1013
1041
  return feature_config_dict
1014
1042
 
@@ -10,7 +10,7 @@ from keras_rs.src.api_export import keras_rs_export
10
10
 
11
11
 
12
12
  @keras_rs_export("keras_rs.layers.TableConfig")
13
- @dataclasses.dataclass(eq=True, unsafe_hash=True, order=True)
13
+ @dataclasses.dataclass(order=True)
14
14
  class TableConfig:
15
15
  """Configuration for one embedding table.
16
16
 
@@ -88,7 +88,7 @@ class TableConfig:
88
88
 
89
89
 
90
90
  @keras_rs_export("keras_rs.layers.FeatureConfig")
91
- @dataclasses.dataclass(eq=True, unsafe_hash=True, order=True)
91
+ @dataclasses.dataclass(order=True)
92
92
  class FeatureConfig:
93
93
  """Configuration for one embedding feature.
94
94
 
@@ -102,7 +102,10 @@ class FeatureConfig:
102
102
  input_shape: The input shape of the feature. The feature fed into the
103
103
  layer has to match the shape. Note that for ragged dimensions in the
104
104
  input, the dimension provided here presents the maximum value;
105
- anything larger will be truncated.
105
+ anything larger will be truncated. Also note that the first
106
+ dimension represents the global batch size. For example, on TPU,
107
+ this represents the total number of samples that are dispatched to
108
+ all the TPUs connected to the current host.
106
109
  output_shape: The output shape of the feature activation. What is
107
110
  returned by the embedding layer has to match this shape.
108
111
  """
@@ -0,0 +1,104 @@
1
+ """A Wrapper over orbax CheckpointManager for Keras3 Jax TPU Embeddings."""
2
+
3
+ from typing import Any
4
+
5
+ import keras
6
+ import orbax.checkpoint as ocp
7
+ from etils import epath
8
+
9
+
10
+ class JaxKeras3CheckpointManager(ocp.CheckpointManager):
11
+ """A wrapper over orbax CheckpointManager for Keras3 Jax TPU Embeddings."""
12
+
13
+ def __init__(
14
+ self,
15
+ model: keras.Model,
16
+ checkpoint_dir: epath.PathLike,
17
+ max_to_keep: int,
18
+ steps_per_epoch: int = 1,
19
+ **kwargs: Any,
20
+ ):
21
+ options = ocp.CheckpointManagerOptions(
22
+ max_to_keep=max_to_keep, enable_async_checkpointing=False, **kwargs
23
+ )
24
+ self._model = model
25
+ self._steps_per_epoch = steps_per_epoch
26
+ self._checkpoint_dir = checkpoint_dir
27
+ super().__init__(checkpoint_dir, options=options)
28
+
29
+ def _get_state(self) -> tuple[dict[str, Any], Any | None]:
30
+ """Gets the model state and metrics"""
31
+ model_state = self._model.get_state_tree()
32
+ state = {}
33
+ metrics = None
34
+ for k, v in model_state.items():
35
+ if k == "metrics_variables":
36
+ metrics = v
37
+ else:
38
+ state[k] = v
39
+ return state, metrics
40
+
41
+ def save_state(self, epoch: int) -> None:
42
+ """Saves the model to the checkpoint directory.
43
+
44
+ Args:
45
+ epoch: The epoch number at which the state is saved.
46
+ """
47
+ state, metrics_value = self._get_state()
48
+ self.save(
49
+ epoch * self._steps_per_epoch,
50
+ args=ocp.args.StandardSave(item=state),
51
+ metrics=metrics_value,
52
+ )
53
+
54
+ def restore_state(self, step: int | None = None) -> None:
55
+ """Restores the model from the checkpoint directory.
56
+
57
+ Args:
58
+ step: The step .number to restore the state from. Default=None
59
+ restores the latest step.
60
+ """
61
+ if step is None:
62
+ step = self.latest_step()
63
+ # Restore the model state only, not metrics.
64
+ state, _ = self._get_state()
65
+ restored_state = self.restore(
66
+ step, args=ocp.args.StandardRestore(item=state)
67
+ )
68
+ self._model.set_state_tree(restored_state)
69
+
70
+
71
+ class JaxKeras3CheckpointCallback(keras.callbacks.Callback):
72
+ """A callback for checkpointing and restoring state using Orbax."""
73
+
74
+ def __init__(
75
+ self,
76
+ model: keras.Model,
77
+ checkpoint_dir: epath.PathLike,
78
+ max_to_keep: int,
79
+ steps_per_epoch: int = 1,
80
+ **kwargs: Any,
81
+ ):
82
+ if keras.backend.backend() != "jax":
83
+ raise ValueError(
84
+ "`JaxKeras3CheckpointCallback` is only supported on a "
85
+ "`jax` backend."
86
+ )
87
+ self._checkpoint_manager = JaxKeras3CheckpointManager(
88
+ model, checkpoint_dir, max_to_keep, steps_per_epoch, **kwargs
89
+ )
90
+
91
+ def on_train_begin(self, logs: dict[str, Any] | None = None) -> None:
92
+ if not self.model.built or not self.model.optimizer.built:
93
+ raise ValueError(
94
+ "To use `JaxKeras3CheckpointCallback`, your model and "
95
+ "optimizer must be built before you call `fit()`."
96
+ )
97
+ latest_epoch = self._checkpoint_manager.latest_step()
98
+ if latest_epoch is not None:
99
+ self._checkpoint_manager.restore_state(step=latest_epoch)
100
+
101
+ def on_epoch_end(
102
+ self, epoch: int, logs: dict[str, Any] | None = None
103
+ ) -> None:
104
+ self._checkpoint_manager.save_state(epoch)
@@ -229,18 +229,63 @@ def keras_to_jte_optimizer(
229
229
  # pylint: disable-next=protected-access
230
230
  learning_rate = keras_to_jte_learning_rate(optimizer._learning_rate)
231
231
 
232
- # SGD or Adagrad
232
+ # Unsupported keras optimizer general options.
233
+ if optimizer.clipnorm is not None:
234
+ raise ValueError("Unsupported optimizer option `clipnorm`.")
235
+ if optimizer.global_clipnorm is not None:
236
+ raise ValueError("Unsupported optimizer option `global_clipnorm`.")
237
+ if optimizer.use_ema:
238
+ raise ValueError("Unsupported optimizer option `use_ema`.")
239
+ if optimizer.loss_scale_factor is not None:
240
+ raise ValueError("Unsupported optimizer option `loss_scale_factor`.")
241
+
242
+ # Supported optimizers.
233
243
  if isinstance(optimizer, keras.optimizers.SGD):
244
+ if getattr(optimizer, "nesterov", False):
245
+ raise ValueError("Unsupported optimizer option `nesterov`.")
246
+ if getattr(optimizer, "momentum", 0.0) != 0.0:
247
+ raise ValueError("Unsupported optimizer option `momentum`.")
234
248
  return embedding_spec.SGDOptimizerSpec(learning_rate=learning_rate)
235
249
  elif isinstance(optimizer, keras.optimizers.Adagrad):
250
+ if getattr(optimizer, "epsilon", 1e-7) != 1e-7:
251
+ raise ValueError("Unsupported optimizer option `epsilon`.")
236
252
  return embedding_spec.AdagradOptimizerSpec(
237
253
  learning_rate=learning_rate,
238
254
  initial_accumulator_value=optimizer.initial_accumulator_value,
239
255
  )
256
+ elif isinstance(optimizer, keras.optimizers.Adam):
257
+ if getattr(optimizer, "amsgrad", False):
258
+ raise ValueError("Unsupported optimizer option `amsgrad`.")
240
259
 
241
- # Default to SGD for now, since other optimizers are still being created,
242
- # and we don't want to fail.
243
- return embedding_spec.SGDOptimizerSpec(learning_rate=learning_rate)
260
+ return embedding_spec.AdamOptimizerSpec(
261
+ learning_rate=learning_rate,
262
+ beta_1=optimizer.beta_1,
263
+ beta_2=optimizer.beta_2,
264
+ epsilon=optimizer.epsilon,
265
+ )
266
+ elif isinstance(optimizer, keras.optimizers.Ftrl):
267
+ if (
268
+ getattr(optimizer, "l2_shrinkage_regularization_strength", 0.0)
269
+ != 0.0
270
+ ):
271
+ raise ValueError(
272
+ "Unsupported optimizer option "
273
+ "`l2_shrinkage_regularization_strength`."
274
+ )
275
+
276
+ return embedding_spec.FTRLOptimizerSpec(
277
+ learning_rate=learning_rate,
278
+ learning_rate_power=optimizer.learning_rate_power,
279
+ l1_regularization_strength=optimizer.l1_regularization_strength,
280
+ l2_regularization_strength=optimizer.l2_regularization_strength,
281
+ beta=optimizer.beta,
282
+ initial_accumulator_value=optimizer.initial_accumulator_value,
283
+ )
284
+
285
+ raise ValueError(
286
+ f"Unsupported optimizer type {type(optimizer)}. Optimizer must be "
287
+ f"one of [Adagrad, Adam, Ftrl, SGD]."
288
+ )
244
289
 
245
290
 
246
291
  def jte_to_keras_optimizer(
@@ -262,8 +307,33 @@ def jte_to_keras_optimizer(
262
307
  learning_rate=learning_rate,
263
308
  initial_accumulator_value=optimizer.initial_accumulator_value,
264
309
  )
310
+ elif isinstance(optimizer, embedding_spec.AdamOptimizerSpec):
311
+ return keras.optimizers.Adam(
312
+ learning_rate=learning_rate,
313
+ beta_1=optimizer.beta_1,
314
+ beta_2=optimizer.beta_2,
315
+ epsilon=optimizer.epsilon,
316
+ )
317
+ elif isinstance(optimizer, embedding_spec.FTRLOptimizerSpec):
318
+ if getattr(optimizer, "initial_linear_value", 0.0) != 0.0:
319
+ raise ValueError(
320
+ "Unsupported optimizer option `initial_linear_value`."
321
+ )
322
+ if getattr(optimizer, "multiply_linear_by_learning_rate", False):
323
+ raise ValueError(
324
+ "Unsupported optimizer option "
325
+ "`multiply_linear_by_learning_rate`."
326
+ )
327
+ return keras.optimizers.Ftrl(
328
+ learning_rate=learning_rate,
329
+ learning_rate_power=optimizer.learning_rate_power,
330
+ initial_accumulator_value=optimizer.initial_accumulator_value,
331
+ l1_regularization_strength=optimizer.l1_regularization_strength,
332
+ l2_regularization_strength=optimizer.l2_regularization_strength,
333
+ beta=optimizer.beta,
334
+ )
265
335
 
266
- raise ValueError(f"Unknown optimizer spec {optimizer}")
336
+ raise ValueError(f"Unknown optimizer spec {type(optimizer)}.")
267
337
 
268
338
 
269
339
  def _keras_to_jte_table_config(