keras-rs 0.3.0.dev0__tar.gz → 0.4.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 (64) hide show
  1. {keras_rs-0.3.0.dev0 → keras_rs-0.4.0.dev0}/PKG-INFO +1 -1
  2. {keras_rs-0.3.0.dev0 → keras_rs-0.4.0.dev0}/keras_rs/api/losses/__init__.py +1 -0
  3. {keras_rs-0.3.0.dev0 → keras_rs-0.4.0.dev0}/keras_rs/src/layers/embedding/base_distributed_embedding.py +7 -0
  4. {keras_rs-0.3.0.dev0 → keras_rs-0.4.0.dev0}/keras_rs/src/layers/embedding/jax/distributed_embedding.py +112 -47
  5. {keras_rs-0.3.0.dev0 → keras_rs-0.4.0.dev0}/keras_rs/src/layers/embedding/jax/embedding_lookup.py +25 -4
  6. keras_rs-0.4.0.dev0/keras_rs/src/layers/embedding/jax/embedding_utils.py +217 -0
  7. {keras_rs-0.3.0.dev0 → keras_rs-0.4.0.dev0}/keras_rs/src/layers/embedding/tensorflow/distributed_embedding.py +7 -0
  8. keras_rs-0.4.0.dev0/keras_rs/src/losses/list_mle_loss.py +212 -0
  9. {keras_rs-0.3.0.dev0 → keras_rs-0.4.0.dev0}/keras_rs/src/metrics/ranking_metrics_utils.py +21 -2
  10. keras_rs-0.4.0.dev0/keras_rs/src/utils/tpu_test_utils.py +120 -0
  11. {keras_rs-0.3.0.dev0 → keras_rs-0.4.0.dev0}/keras_rs/src/version.py +1 -1
  12. {keras_rs-0.3.0.dev0 → keras_rs-0.4.0.dev0}/keras_rs.egg-info/PKG-INFO +1 -1
  13. {keras_rs-0.3.0.dev0 → keras_rs-0.4.0.dev0}/keras_rs.egg-info/SOURCES.txt +3 -1
  14. {keras_rs-0.3.0.dev0 → keras_rs-0.4.0.dev0}/pyproject.toml +1 -1
  15. keras_rs-0.3.0.dev0/keras_rs/src/layers/embedding/jax/embedding_utils.py +0 -642
  16. {keras_rs-0.3.0.dev0 → keras_rs-0.4.0.dev0}/README.md +0 -0
  17. {keras_rs-0.3.0.dev0 → keras_rs-0.4.0.dev0}/keras_rs/api/__init__.py +0 -0
  18. {keras_rs-0.3.0.dev0 → keras_rs-0.4.0.dev0}/keras_rs/api/layers/__init__.py +0 -0
  19. {keras_rs-0.3.0.dev0 → keras_rs-0.4.0.dev0}/keras_rs/api/metrics/__init__.py +0 -0
  20. {keras_rs-0.3.0.dev0 → keras_rs-0.4.0.dev0}/keras_rs/src/__init__.py +0 -0
  21. {keras_rs-0.3.0.dev0 → keras_rs-0.4.0.dev0}/keras_rs/src/api_export.py +0 -0
  22. {keras_rs-0.3.0.dev0 → keras_rs-0.4.0.dev0}/keras_rs/src/layers/__init__.py +0 -0
  23. {keras_rs-0.3.0.dev0 → keras_rs-0.4.0.dev0}/keras_rs/src/layers/embedding/__init__.py +0 -0
  24. {keras_rs-0.3.0.dev0 → keras_rs-0.4.0.dev0}/keras_rs/src/layers/embedding/distributed_embedding.py +0 -0
  25. {keras_rs-0.3.0.dev0 → keras_rs-0.4.0.dev0}/keras_rs/src/layers/embedding/distributed_embedding_config.py +0 -0
  26. {keras_rs-0.3.0.dev0 → keras_rs-0.4.0.dev0}/keras_rs/src/layers/embedding/embed_reduce.py +0 -0
  27. {keras_rs-0.3.0.dev0 → keras_rs-0.4.0.dev0}/keras_rs/src/layers/embedding/jax/__init__.py +0 -0
  28. {keras_rs-0.3.0.dev0 → keras_rs-0.4.0.dev0}/keras_rs/src/layers/embedding/jax/checkpoint_utils.py +0 -0
  29. {keras_rs-0.3.0.dev0 → keras_rs-0.4.0.dev0}/keras_rs/src/layers/embedding/jax/config_conversion.py +0 -0
  30. {keras_rs-0.3.0.dev0 → keras_rs-0.4.0.dev0}/keras_rs/src/layers/embedding/tensorflow/__init__.py +0 -0
  31. {keras_rs-0.3.0.dev0 → keras_rs-0.4.0.dev0}/keras_rs/src/layers/embedding/tensorflow/config_conversion.py +0 -0
  32. {keras_rs-0.3.0.dev0 → keras_rs-0.4.0.dev0}/keras_rs/src/layers/feature_interaction/__init__.py +0 -0
  33. {keras_rs-0.3.0.dev0 → keras_rs-0.4.0.dev0}/keras_rs/src/layers/feature_interaction/dot_interaction.py +0 -0
  34. {keras_rs-0.3.0.dev0 → keras_rs-0.4.0.dev0}/keras_rs/src/layers/feature_interaction/feature_cross.py +0 -0
  35. {keras_rs-0.3.0.dev0 → keras_rs-0.4.0.dev0}/keras_rs/src/layers/retrieval/__init__.py +0 -0
  36. {keras_rs-0.3.0.dev0 → keras_rs-0.4.0.dev0}/keras_rs/src/layers/retrieval/brute_force_retrieval.py +0 -0
  37. {keras_rs-0.3.0.dev0 → keras_rs-0.4.0.dev0}/keras_rs/src/layers/retrieval/hard_negative_mining.py +0 -0
  38. {keras_rs-0.3.0.dev0 → keras_rs-0.4.0.dev0}/keras_rs/src/layers/retrieval/remove_accidental_hits.py +0 -0
  39. {keras_rs-0.3.0.dev0 → keras_rs-0.4.0.dev0}/keras_rs/src/layers/retrieval/retrieval.py +0 -0
  40. {keras_rs-0.3.0.dev0 → keras_rs-0.4.0.dev0}/keras_rs/src/layers/retrieval/sampling_probability_correction.py +0 -0
  41. {keras_rs-0.3.0.dev0 → keras_rs-0.4.0.dev0}/keras_rs/src/losses/__init__.py +0 -0
  42. {keras_rs-0.3.0.dev0 → keras_rs-0.4.0.dev0}/keras_rs/src/losses/pairwise_hinge_loss.py +0 -0
  43. {keras_rs-0.3.0.dev0 → keras_rs-0.4.0.dev0}/keras_rs/src/losses/pairwise_logistic_loss.py +0 -0
  44. {keras_rs-0.3.0.dev0 → keras_rs-0.4.0.dev0}/keras_rs/src/losses/pairwise_loss.py +0 -0
  45. {keras_rs-0.3.0.dev0 → keras_rs-0.4.0.dev0}/keras_rs/src/losses/pairwise_loss_utils.py +0 -0
  46. {keras_rs-0.3.0.dev0 → keras_rs-0.4.0.dev0}/keras_rs/src/losses/pairwise_mean_squared_error.py +0 -0
  47. {keras_rs-0.3.0.dev0 → keras_rs-0.4.0.dev0}/keras_rs/src/losses/pairwise_soft_zero_one_loss.py +0 -0
  48. {keras_rs-0.3.0.dev0 → keras_rs-0.4.0.dev0}/keras_rs/src/metrics/__init__.py +0 -0
  49. {keras_rs-0.3.0.dev0 → keras_rs-0.4.0.dev0}/keras_rs/src/metrics/dcg.py +0 -0
  50. {keras_rs-0.3.0.dev0 → keras_rs-0.4.0.dev0}/keras_rs/src/metrics/mean_average_precision.py +0 -0
  51. {keras_rs-0.3.0.dev0 → keras_rs-0.4.0.dev0}/keras_rs/src/metrics/mean_reciprocal_rank.py +0 -0
  52. {keras_rs-0.3.0.dev0 → keras_rs-0.4.0.dev0}/keras_rs/src/metrics/ndcg.py +0 -0
  53. {keras_rs-0.3.0.dev0 → keras_rs-0.4.0.dev0}/keras_rs/src/metrics/precision_at_k.py +0 -0
  54. {keras_rs-0.3.0.dev0 → keras_rs-0.4.0.dev0}/keras_rs/src/metrics/ranking_metric.py +0 -0
  55. {keras_rs-0.3.0.dev0 → keras_rs-0.4.0.dev0}/keras_rs/src/metrics/recall_at_k.py +0 -0
  56. {keras_rs-0.3.0.dev0 → keras_rs-0.4.0.dev0}/keras_rs/src/metrics/utils.py +0 -0
  57. {keras_rs-0.3.0.dev0 → keras_rs-0.4.0.dev0}/keras_rs/src/types.py +0 -0
  58. {keras_rs-0.3.0.dev0 → keras_rs-0.4.0.dev0}/keras_rs/src/utils/__init__.py +0 -0
  59. {keras_rs-0.3.0.dev0 → keras_rs-0.4.0.dev0}/keras_rs/src/utils/doc_string_utils.py +0 -0
  60. {keras_rs-0.3.0.dev0 → keras_rs-0.4.0.dev0}/keras_rs/src/utils/keras_utils.py +0 -0
  61. {keras_rs-0.3.0.dev0 → keras_rs-0.4.0.dev0}/keras_rs.egg-info/dependency_links.txt +0 -0
  62. {keras_rs-0.3.0.dev0 → keras_rs-0.4.0.dev0}/keras_rs.egg-info/requires.txt +0 -0
  63. {keras_rs-0.3.0.dev0 → keras_rs-0.4.0.dev0}/keras_rs.egg-info/top_level.txt +0 -0
  64. {keras_rs-0.3.0.dev0 → keras_rs-0.4.0.dev0}/setup.cfg +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: keras-rs
3
- Version: 0.3.0.dev0
3
+ Version: 0.4.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
@@ -4,6 +4,7 @@ This file was autogenerated. Do not edit it by hand,
4
4
  since your modifications would be overwritten.
5
5
  """
6
6
 
7
+ from keras_rs.src.losses.list_mle_loss import ListMLELoss as ListMLELoss
7
8
  from keras_rs.src.losses.pairwise_hinge_loss import (
8
9
  PairwiseHingeLoss as PairwiseHingeLoss,
9
10
  )
@@ -457,6 +457,10 @@ class DistributedEmbedding(keras.layers.Layer):
457
457
  tables in the inner lists together. Note that table stacking is not
458
458
  supported on older TPUs, in which case the default value of `"auto"`
459
459
  will be interpreted as no table stacking.
460
+ update_stats: If True, `'max_ids_per_partition'`,
461
+ `'max_unique_ids_per_partition'` and
462
+ `'suggested_coo_buffer_size_per_device'` are updated during
463
+ training. This argument can be set to True only for the JAX backend.
460
464
  **kwargs: Additional arguments to pass to the layer base class.
461
465
  """
462
466
 
@@ -467,6 +471,7 @@ class DistributedEmbedding(keras.layers.Layer):
467
471
  table_stacking: (
468
472
  str | Sequence[str] | Sequence[Sequence[str]]
469
473
  ) = "auto",
474
+ update_stats: bool = False,
470
475
  **kwargs: Any,
471
476
  ) -> None:
472
477
  super().__init__(**kwargs)
@@ -486,6 +491,8 @@ class DistributedEmbedding(keras.layers.Layer):
486
491
  table_stacking,
487
492
  )
488
493
 
494
+ self.update_stats = update_stats
495
+
489
496
  @keras_utils.no_automatic_dependency_tracking
490
497
  def _init_feature_configs_structures(
491
498
  self,
@@ -9,6 +9,7 @@ import keras
9
9
  import numpy as np
10
10
  from jax import numpy as jnp
11
11
  from jax.experimental import layout as jax_layout
12
+ from jax.experimental import multihost_utils
12
13
  from jax_tpu_embedding.sparsecore.lib.nn import embedding
13
14
  from jax_tpu_embedding.sparsecore.lib.nn import embedding_spec
14
15
  from jax_tpu_embedding.sparsecore.lib.nn import (
@@ -27,9 +28,14 @@ from keras_rs.src.layers.embedding.jax import embedding_utils
27
28
  from keras_rs.src.types import Nested
28
29
  from keras_rs.src.utils import keras_utils
29
30
 
31
+ if jax.__version_info__ >= (0, 8, 0):
32
+ from jax import shard_map
33
+ else:
34
+ from jax.experimental.shard_map import shard_map # type: ignore[assignment]
35
+
36
+
30
37
  ArrayLike = Union[np.ndarray[Any, Any], jax.Array]
31
38
  FeatureConfig = config.FeatureConfig
32
- shard_map = jax.experimental.shard_map.shard_map # type: ignore[attr-defined]
33
39
 
34
40
 
35
41
  def _get_partition_spec(
@@ -265,7 +271,7 @@ class DistributedEmbedding(base_distributed_embedding.DistributedEmbedding):
265
271
  table_specs: Sequence[embedding_spec.TableSpec],
266
272
  num_shards: int,
267
273
  add_slot_variables: bool,
268
- ) -> tuple[keras.Variable, tuple[keras.Variable, ...] | None]:
274
+ ) -> embedding.EmbeddingVariables:
269
275
  stacked_table_spec = typing.cast(
270
276
  embedding_spec.StackedTableSpec, table_specs[0].stacked_table_spec
271
277
  )
@@ -334,7 +340,7 @@ class DistributedEmbedding(base_distributed_embedding.DistributedEmbedding):
334
340
  slot_initializers, slot_variables
335
341
  )
336
342
 
337
- return table_variable, slot_variables
343
+ return embedding.EmbeddingVariables(table_variable, slot_variables)
338
344
 
339
345
  @keras_utils.no_automatic_dependency_tracking
340
346
  def _sparsecore_init(
@@ -401,7 +407,9 @@ class DistributedEmbedding(base_distributed_embedding.DistributedEmbedding):
401
407
  if isinstance(table_stacking, str):
402
408
  if table_stacking == "auto":
403
409
  jte_table_stacking.auto_stack_tables(
404
- feature_specs, global_device_count, num_sc_per_device
410
+ feature_specs,
411
+ global_device_count,
412
+ num_sc_per_device,
405
413
  )
406
414
  else:
407
415
  raise ValueError(
@@ -441,8 +449,51 @@ class DistributedEmbedding(base_distributed_embedding.DistributedEmbedding):
441
449
  )
442
450
 
443
451
  # Collect all stacked tables.
444
- table_specs = embedding_utils.get_table_specs(feature_specs)
445
- table_stacks = embedding_utils.get_table_stacks(table_specs)
452
+ table_specs = embedding.get_table_specs(feature_specs)
453
+ table_stacks = jte_table_stacking.get_table_stacks(table_specs)
454
+
455
+ # Update stacked table stats to max of values across involved tables.
456
+ max_ids_per_partition = {}
457
+ max_unique_ids_per_partition = {}
458
+ required_buffer_size_per_device = {}
459
+ id_drop_counters = {}
460
+ for stack_name, stack in table_stacks.items():
461
+ max_ids_per_partition[stack_name] = np.max(
462
+ np.asarray(
463
+ [s.max_ids_per_partition for s in stack], dtype=np.int32
464
+ )
465
+ )
466
+ max_unique_ids_per_partition[stack_name] = np.max(
467
+ np.asarray(
468
+ [s.max_unique_ids_per_partition for s in stack],
469
+ dtype=np.int32,
470
+ )
471
+ )
472
+
473
+ # Only set the suggested buffer size if set on any individual table.
474
+ valid_buffer_sizes = [
475
+ s.suggested_coo_buffer_size_per_device
476
+ for s in stack
477
+ if s.suggested_coo_buffer_size_per_device is not None
478
+ ]
479
+ if valid_buffer_sizes:
480
+ required_buffer_size_per_device[stack_name] = np.max(
481
+ np.asarray(valid_buffer_sizes, dtype=np.int32)
482
+ )
483
+
484
+ id_drop_counters[stack_name] = 0
485
+
486
+ aggregated_stats = embedding.SparseDenseMatmulInputStats(
487
+ max_ids_per_partition=max_ids_per_partition,
488
+ max_unique_ids_per_partition=max_unique_ids_per_partition,
489
+ required_buffer_size_per_sc=required_buffer_size_per_device,
490
+ id_drop_counters=id_drop_counters,
491
+ )
492
+ embedding.update_preprocessing_parameters(
493
+ feature_specs,
494
+ aggregated_stats,
495
+ num_sc_per_device,
496
+ )
446
497
 
447
498
  # Create variables for all stacked tables and slot variables.
448
499
  with sparsecore_distribution.scope():
@@ -515,10 +566,8 @@ class DistributedEmbedding(base_distributed_embedding.DistributedEmbedding):
515
566
  del inputs, weights, training
516
567
 
517
568
  # Each stacked-table gets a ShardedCooMatrix.
518
- table_specs = embedding_utils.get_table_specs(
519
- self._config.feature_specs
520
- )
521
- table_stacks = embedding_utils.get_table_stacks(table_specs)
569
+ table_specs = embedding.get_table_specs(self._config.feature_specs)
570
+ table_stacks = jte_table_stacking.get_table_stacks(table_specs)
522
571
  stacked_table_specs = {
523
572
  stack_name: stack[0].stacked_table_spec
524
573
  for stack_name, stack in table_stacks.items()
@@ -597,43 +646,57 @@ class DistributedEmbedding(base_distributed_embedding.DistributedEmbedding):
597
646
  num_sc_per_device,
598
647
  )
599
648
 
600
- if training:
649
+ if training and self.update_stats:
601
650
  # Synchronize input statistics across all devices and update the
602
651
  # underlying stacked tables specs in the feature specs.
603
- prev_stats = embedding_utils.get_stacked_table_stats(
604
- self._config.feature_specs
605
- )
606
-
607
- # Take the maximum with existing stats.
608
- stats = keras.tree.map_structure(max, prev_stats, stats)
609
652
 
610
- # Flatten the stats so we can more efficiently transfer them
611
- # between hosts. We use jax.tree because we will later need to
612
- # unflatten.
613
- flat_stats, stats_treedef = jax.tree.flatten(stats)
653
+ # Gather stats across all processes/devices via process_allgather.
654
+ all_stats = multihost_utils.process_allgather(stats)
655
+ all_stats = jax.tree.map(np.max, all_stats)
614
656
 
615
- # In the case of multiple local CPU devices per host, we need to
616
- # replicate the stats to placate JAX collectives.
617
- num_local_cpu_devices = jax.local_device_count("cpu")
618
- tiled_stats = np.tile(
619
- np.array(flat_stats, dtype=np.int32), (num_local_cpu_devices, 1)
657
+ # Check if stats changed enough to warrant action.
658
+ stacked_table_specs = embedding.get_stacked_table_specs(
659
+ self._config.feature_specs
620
660
  )
621
-
622
- # Aggregate variables across all processes/devices.
623
- max_across_cpus = jax.pmap(
624
- lambda x: jax.lax.pmax( # type: ignore[no-untyped-call]
625
- x, "all_cpus"
626
- ),
627
- axis_name="all_cpus",
628
- backend="cpu",
661
+ changed = any(
662
+ all_stats.max_ids_per_partition[stack_name]
663
+ > spec.max_ids_per_partition
664
+ or all_stats.max_unique_ids_per_partition[stack_name]
665
+ > spec.max_unique_ids_per_partition
666
+ or all_stats.required_buffer_size_per_sc[stack_name]
667
+ * num_sc_per_device
668
+ > (spec.suggested_coo_buffer_size_per_device or 0)
669
+ for stack_name, spec in stacked_table_specs.items()
629
670
  )
630
- flat_stats = max_across_cpus(tiled_stats)[0].tolist()
631
- stats = jax.tree.unflatten(stats_treedef, flat_stats)
632
671
 
633
672
  # Update configuration and repeat preprocessing if stats changed.
634
- if stats != prev_stats:
635
- embedding_utils.update_stacked_table_stats(
636
- self._config.feature_specs, stats
673
+ if changed:
674
+ for stack_name, spec in stacked_table_specs.items():
675
+ all_stats.max_ids_per_partition[stack_name] = np.max(
676
+ [
677
+ all_stats.max_ids_per_partition[stack_name],
678
+ spec.max_ids_per_partition,
679
+ ]
680
+ )
681
+ all_stats.max_unique_ids_per_partition[stack_name] = np.max(
682
+ [
683
+ all_stats.max_unique_ids_per_partition[stack_name],
684
+ spec.max_unique_ids_per_partition,
685
+ ]
686
+ )
687
+ all_stats.required_buffer_size_per_sc[stack_name] = np.max(
688
+ [
689
+ all_stats.required_buffer_size_per_sc[stack_name],
690
+ (
691
+ (spec.suggested_coo_buffer_size_per_device or 0)
692
+ + (num_sc_per_device - 1)
693
+ )
694
+ // num_sc_per_device,
695
+ ]
696
+ )
697
+
698
+ embedding.update_preprocessing_parameters(
699
+ self._config.feature_specs, all_stats, num_sc_per_device
637
700
  )
638
701
 
639
702
  # Re-execute preprocessing with consistent input statistics.
@@ -718,8 +781,8 @@ class DistributedEmbedding(base_distributed_embedding.DistributedEmbedding):
718
781
 
719
782
  config = self._config
720
783
  num_table_shards = config.mesh.devices.size * config.num_sc_per_device
721
- table_specs = embedding_utils.get_table_specs(config.feature_specs)
722
- sharded_tables = embedding_utils.stack_and_shard_tables(
784
+ table_specs = embedding.get_table_specs(config.feature_specs)
785
+ sharded_tables = jte_table_stacking.stack_and_shard_tables(
723
786
  table_specs,
724
787
  tables,
725
788
  num_table_shards,
@@ -738,8 +801,8 @@ class DistributedEmbedding(base_distributed_embedding.DistributedEmbedding):
738
801
  # Assign stacked table variables to the device values.
739
802
  keras.tree.map_structure_up_to(
740
803
  device_tables,
741
- lambda table_and_slot_variables,
742
- table_value: table_and_slot_variables[0].assign(table_value),
804
+ lambda embedding_variables,
805
+ table_value: embedding_variables.table.assign(table_value),
743
806
  self._table_and_slot_variables,
744
807
  device_tables,
745
808
  )
@@ -750,17 +813,19 @@ class DistributedEmbedding(base_distributed_embedding.DistributedEmbedding):
750
813
 
751
814
  config = self._config
752
815
  num_table_shards = config.mesh.devices.size * config.num_sc_per_device
753
- table_specs = embedding_utils.get_table_specs(config.feature_specs)
816
+ table_specs = embedding.get_table_specs(config.feature_specs)
754
817
 
755
818
  # Extract only the table variables, not the gradient slot variables.
756
819
  table_variables = {
757
- name: jax.device_get(table_and_slots[0].value)
758
- for name, table_and_slots in self._table_and_slot_variables.items()
820
+ name: jax.device_get(embedding_variables.table.value)
821
+ for name, embedding_variables in (
822
+ self._table_and_slot_variables.items()
823
+ )
759
824
  }
760
825
 
761
826
  return typing.cast(
762
827
  dict[str, ArrayLike],
763
- embedding_utils.unshard_and_unstack_tables(
828
+ jte_table_stacking.unshard_and_unstack_tables(
764
829
  table_specs, table_variables, num_table_shards
765
830
  ),
766
831
  )
@@ -16,9 +16,30 @@ from jax_tpu_embedding.sparsecore.utils import utils as jte_utils
16
16
  from keras_rs.src.layers.embedding.jax import embedding_utils
17
17
  from keras_rs.src.types import Nested
18
18
 
19
- ShardedCooMatrix = embedding_utils.ShardedCooMatrix
20
- shard_map = jax.experimental.shard_map.shard_map # type: ignore[attr-defined]
19
+ if jax.__version_info__ >= (0, 8, 0):
20
+ from jax import shard_map
21
+ else:
22
+ from jax.experimental.shard_map import shard_map as exp_shard_map
23
+
24
+ def shard_map( # type: ignore[misc]
25
+ f: Any = None,
26
+ /,
27
+ *,
28
+ out_specs: Any,
29
+ in_specs: Any,
30
+ mesh: Any = None,
31
+ check_vma: bool = True,
32
+ ) -> Any:
33
+ return exp_shard_map(
34
+ f,
35
+ mesh=mesh,
36
+ in_specs=in_specs,
37
+ out_specs=out_specs,
38
+ check_rep=check_vma,
39
+ ) # type: ignore[no-untyped-call]
40
+
21
41
 
42
+ ShardedCooMatrix = embedding_utils.ShardedCooMatrix
22
43
  ArrayLike: TypeAlias = jax.Array | np.ndarray[Any, Any]
23
44
  JaxLayout: TypeAlias = jax.sharding.NamedSharding | jax_layout.Format
24
45
 
@@ -121,7 +142,7 @@ def embedding_lookup(
121
142
  mesh=config.mesh,
122
143
  in_specs=(pd, pt),
123
144
  out_specs=pd,
124
- check_rep=False,
145
+ check_vma=False,
125
146
  ),
126
147
  )
127
148
 
@@ -220,7 +241,7 @@ def embedding_lookup_bwd(
220
241
  mesh=config.mesh,
221
242
  in_specs=(pd, pd, pt, preplicate),
222
243
  out_specs=pt,
223
- check_rep=False,
244
+ check_vma=False,
224
245
  ),
225
246
  # in_shardings=(
226
247
  # activation_layout,
@@ -0,0 +1,217 @@
1
+ """Utility functions for manipulating JAX embedding tables and inputs."""
2
+
3
+ import collections
4
+ from typing import Any, Mapping, NamedTuple, Sequence, TypeAlias, TypeVar
5
+
6
+ import jax
7
+ import numpy as np
8
+ from jax_tpu_embedding.sparsecore.lib.nn import embedding
9
+ from jax_tpu_embedding.sparsecore.lib.nn import table_stacking
10
+ from jax_tpu_embedding.sparsecore.lib.nn.embedding_spec import FeatureSpec
11
+
12
+ from keras_rs.src.types import Nested
13
+
14
+ T = TypeVar("T")
15
+
16
+ # Any to support tf.Ragged without needing an explicit TF dependency.
17
+ ArrayLike: TypeAlias = jax.Array | np.ndarray | Any # type: ignore
18
+ Shape: TypeAlias = tuple[int, ...]
19
+
20
+
21
+ class FeatureSamples(NamedTuple):
22
+ tokens: ArrayLike
23
+ weights: ArrayLike | None
24
+
25
+
26
+ class ShardedCooMatrix(NamedTuple):
27
+ shard_starts: ArrayLike
28
+ shard_ends: ArrayLike
29
+ col_ids: ArrayLike
30
+ row_ids: ArrayLike
31
+ values: ArrayLike
32
+
33
+
34
+ def convert_to_numpy(
35
+ ragged_or_dense: np.ndarray[Any, Any] | Sequence[Sequence[Any]] | Any,
36
+ dtype: Any,
37
+ ) -> np.ndarray[Any, Any]:
38
+ """Converts a ragged or dense list of inputs to a ragged/dense numpy array.
39
+
40
+ The output is adjusted to be 2D.
41
+
42
+ Args:
43
+ ragged_or_dense: Input that is either already a numpy array, or nested
44
+ sequence.
45
+ dtype: Numpy dtype of output array.
46
+
47
+ Returns:
48
+ Corresponding numpy array.
49
+ """
50
+ if hasattr(ragged_or_dense, "numpy"):
51
+ # Support tf.RaggedTensor and other TF input dtypes.
52
+ if callable(getattr(ragged_or_dense, "numpy")):
53
+ ragged_or_dense = ragged_or_dense.numpy()
54
+
55
+ if isinstance(ragged_or_dense, jax.Array):
56
+ ragged_or_dense = np.asarray(ragged_or_dense)
57
+
58
+ if isinstance(ragged_or_dense, np.ndarray):
59
+ # Convert 1D to 2D.
60
+ if ragged_or_dense.dtype != np.ndarray and ragged_or_dense.ndim == 1:
61
+ return ragged_or_dense.reshape(-1, 1).astype(dtype)
62
+
63
+ # If dense, return converted dense type.
64
+ if ragged_or_dense.dtype != np.ndarray:
65
+ return ragged_or_dense.astype(dtype)
66
+
67
+ # Ragged numpy array.
68
+ return ragged_or_dense
69
+
70
+ # Handle 1D sequence input.
71
+ if not isinstance(ragged_or_dense[0], collections.abc.Sequence):
72
+ return np.asarray(ragged_or_dense, dtype=dtype).reshape(-1, 1)
73
+
74
+ # Assemble elements into an nd-array.
75
+ counts = [len(vals) for vals in ragged_or_dense]
76
+ if all([count == counts[0] for count in counts]):
77
+ # Dense input.
78
+ return np.asarray(ragged_or_dense, dtype=dtype)
79
+ else:
80
+ # Ragged input, convert to ragged numpy arrays.
81
+ return np.array(
82
+ [np.array(row, dtype=dtype) for row in ragged_or_dense],
83
+ dtype=np.ndarray,
84
+ )
85
+
86
+
87
+ def create_feature_samples(
88
+ feature_structure: Nested[T],
89
+ feature_ids: Nested[ArrayLike | Sequence[int] | Sequence[Sequence[int]]],
90
+ feature_weights: None
91
+ | (Nested[ArrayLike | Sequence[float] | Sequence[Sequence[float]]]),
92
+ ) -> Nested[FeatureSamples]:
93
+ """Constructs a collection of sample tuples from provided IDs and weights.
94
+
95
+ Args:
96
+ feature_structure: The nested structure of the inputs (typically
97
+ `FeatureSpec`s).
98
+ feature_ids: The feature IDs to use for the samples.
99
+ feature_weights: The feature weights to use for the samples. Defaults
100
+ to ones if not provided.
101
+
102
+ Returns:
103
+ A nested collection of `FeatureSamples` corresponding to the input IDs
104
+ and weights, for use in embedding lookups.
105
+ """
106
+ # Create numpy arrays from inputs.
107
+ feature_ids = jax.tree.map(
108
+ lambda _, ids: convert_to_numpy(ids, np.int32),
109
+ feature_structure,
110
+ feature_ids,
111
+ )
112
+
113
+ if feature_weights is None:
114
+ return jax.tree.map( # type: ignore[no-any-return]
115
+ lambda _, ids: FeatureSamples(ids, None),
116
+ feature_structure,
117
+ feature_ids,
118
+ )
119
+
120
+ feature_weights = jax.tree.map(
121
+ lambda _, wgts: convert_to_numpy(wgts, np.float32),
122
+ feature_structure,
123
+ feature_weights,
124
+ )
125
+
126
+ # Assemble.
127
+ def _create_feature_samples(
128
+ sample_ids: np.ndarray[Any, Any],
129
+ sample_weights: np.ndarray[Any, Any],
130
+ ) -> FeatureSamples:
131
+ return FeatureSamples(sample_ids, sample_weights)
132
+
133
+ output: Nested[FeatureSamples] = jax.tree.map(
134
+ lambda _, sample_ids, sample_weights: _create_feature_samples(
135
+ sample_ids, sample_weights
136
+ ),
137
+ feature_structure,
138
+ feature_ids,
139
+ feature_weights,
140
+ )
141
+ return output
142
+
143
+
144
+ def stack_and_shard_samples(
145
+ feature_specs: Nested[FeatureSpec],
146
+ feature_samples: Nested[FeatureSamples],
147
+ local_device_count: int,
148
+ global_device_count: int,
149
+ num_sc_per_device: int,
150
+ static_buffer_size: int | Mapping[str, int] | None = None,
151
+ ) -> tuple[dict[str, ShardedCooMatrix], embedding.SparseDenseMatmulInputStats]:
152
+ """Prepares input samples for use in embedding lookups.
153
+
154
+ Args:
155
+ feature_specs: Nested collection of feature specifications.
156
+ feature_samples: Nested collection of feature samples.
157
+ local_device_count: Number of local JAX devices.
158
+ global_device_count: Number of global JAX devices.
159
+ num_sc_per_device: Number of sparsecores per device.
160
+ static_buffer_size: The static buffer size to use for the samples.
161
+ Defaults to None, in which case an upper-bound for the buffer size
162
+ will be automatically determined.
163
+
164
+ Returns:
165
+ The preprocessed inputs, and statistics useful for updating FeatureSpecs
166
+ based on the provided input data.
167
+ """
168
+ del static_buffer_size # Currently ignored.
169
+ flat_feature_specs, _ = jax.tree.flatten(feature_specs)
170
+
171
+ feature_tokens = []
172
+ collected_weights = []
173
+
174
+ def collect_tokens_and_weights(
175
+ feature_spec: FeatureSpec, samples: FeatureSamples
176
+ ) -> None:
177
+ del feature_spec
178
+ feature_tokens.append(samples.tokens)
179
+ collected_weights.append(samples.weights)
180
+
181
+ jax.tree.map(collect_tokens_and_weights, feature_specs, feature_samples)
182
+
183
+ feature_weights = (
184
+ None if all(w is None for w in collected_weights) else collected_weights
185
+ )
186
+
187
+ preprocessed_inputs, stats = embedding.preprocess_sparse_dense_matmul_input(
188
+ feature_tokens,
189
+ feature_weights,
190
+ flat_feature_specs,
191
+ local_device_count=local_device_count,
192
+ global_device_count=global_device_count,
193
+ num_sc_per_device=num_sc_per_device,
194
+ sharding_strategy="MOD",
195
+ has_leading_dimension=False,
196
+ allow_id_dropping=True,
197
+ )
198
+
199
+ out: dict[str, ShardedCooMatrix] = {}
200
+ tables_names = preprocessed_inputs.lhs_row_pointers.keys()
201
+ for table_name in tables_names:
202
+ shard_ends = preprocessed_inputs.lhs_row_pointers[table_name]
203
+ shard_starts = np.concatenate(
204
+ [
205
+ np.asarray([0]),
206
+ table_stacking._next_largest_multiple(shard_ends[:-1], 8),
207
+ ]
208
+ )
209
+ out[table_name] = ShardedCooMatrix(
210
+ shard_starts=shard_starts,
211
+ shard_ends=shard_ends,
212
+ col_ids=preprocessed_inputs.lhs_embedding_ids[table_name],
213
+ row_ids=preprocessed_inputs.lhs_sample_ids[table_name],
214
+ values=preprocessed_inputs.lhs_gains[table_name],
215
+ )
216
+
217
+ return out, stats
@@ -35,8 +35,15 @@ class DistributedEmbedding(base_distributed_embedding.DistributedEmbedding):
35
35
  table_stacking: (
36
36
  str | Sequence[str] | Sequence[Sequence[str]]
37
37
  ) = "auto",
38
+ update_stats: bool = False,
38
39
  **kwargs: Any,
39
40
  ) -> None:
41
+ # `update_stats` is supported only on JAX.
42
+ if update_stats:
43
+ raise ValueError(
44
+ "`update_stats` cannot be True for the TensorFlow backend."
45
+ )
46
+
40
47
  # Intercept arguments that are supported only on TensorFlow.
41
48
  self._optimizer = kwargs.pop("optimizer", None)
42
49
  self._pipeline_execution_with_tensor_core = kwargs.pop(