torchrec 0.2.0.dev0__37-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 (167) hide show
  1. examples/__init__.py +0 -0
  2. examples/datasets/__init__.py +8 -0
  3. examples/datasets/criteo_dataframes.py +101 -0
  4. examples/ray/__init__.py +0 -0
  5. examples/ray/compute_world_size.py +51 -0
  6. examples/ray/train_torchrec.py +133 -0
  7. examples/retrieval/__init__.py +6 -0
  8. examples/retrieval/data/__init__.py +6 -0
  9. examples/retrieval/data/dataloader.py +44 -0
  10. examples/retrieval/knn_index.py +67 -0
  11. examples/retrieval/modules/__init__.py +6 -0
  12. examples/retrieval/modules/two_tower.py +229 -0
  13. examples/retrieval/two_tower_retrieval.py +192 -0
  14. examples/retrieval/two_tower_train.py +253 -0
  15. examples/torcharrow/__init__.py +8 -0
  16. examples/torcharrow/dataloader.py +116 -0
  17. examples/torcharrow/run.py +126 -0
  18. fbgemm_gpu/__init__.py +16 -0
  19. fbgemm_gpu/batched_unary_embeddings_ops.py +82 -0
  20. fbgemm_gpu/enums.py +21 -0
  21. fbgemm_gpu/fbgemm_gpu_py.so +0 -0
  22. fbgemm_gpu/permute_pooled_embedding_modules.py +73 -0
  23. fbgemm_gpu/permute_pooled_embedding_modules_split.py +76 -0
  24. fbgemm_gpu/split_embedding_codegen_lookup_invokers/__init__.py +19 -0
  25. fbgemm_gpu/split_embedding_codegen_lookup_invokers/lookup_adagrad.py +120 -0
  26. fbgemm_gpu/split_embedding_codegen_lookup_invokers/lookup_adam.py +149 -0
  27. fbgemm_gpu/split_embedding_codegen_lookup_invokers/lookup_approx_rowwise_adagrad.py +128 -0
  28. fbgemm_gpu/split_embedding_codegen_lookup_invokers/lookup_approx_rowwise_adagrad_with_counter.py +134 -0
  29. fbgemm_gpu/split_embedding_codegen_lookup_invokers/lookup_approx_rowwise_adagrad_with_weight_decay.py +128 -0
  30. fbgemm_gpu/split_embedding_codegen_lookup_invokers/lookup_approx_sgd.py +105 -0
  31. fbgemm_gpu/split_embedding_codegen_lookup_invokers/lookup_args.py +54 -0
  32. fbgemm_gpu/split_embedding_codegen_lookup_invokers/lookup_lamb.py +149 -0
  33. fbgemm_gpu/split_embedding_codegen_lookup_invokers/lookup_lars_sgd.py +128 -0
  34. fbgemm_gpu/split_embedding_codegen_lookup_invokers/lookup_partial_rowwise_adam.py +149 -0
  35. fbgemm_gpu/split_embedding_codegen_lookup_invokers/lookup_partial_rowwise_lamb.py +149 -0
  36. fbgemm_gpu/split_embedding_codegen_lookup_invokers/lookup_rowwise_adagrad.py +128 -0
  37. fbgemm_gpu/split_embedding_codegen_lookup_invokers/lookup_rowwise_adagrad_with_counter.py +134 -0
  38. fbgemm_gpu/split_embedding_codegen_lookup_invokers/lookup_rowwise_adagrad_with_weight_decay.py +128 -0
  39. fbgemm_gpu/split_embedding_codegen_lookup_invokers/lookup_rowwise_weighted_adagrad.py +130 -0
  40. fbgemm_gpu/split_embedding_codegen_lookup_invokers/lookup_sgd.py +105 -0
  41. fbgemm_gpu/split_embedding_configs.py +182 -0
  42. fbgemm_gpu/split_embedding_inference_converter.py +208 -0
  43. fbgemm_gpu/split_table_batched_embeddings_ops.py +2503 -0
  44. fbgemm_gpu/uvm.py +35 -0
  45. torchrec/__init__.py +27 -0
  46. torchrec/datasets/__init__.py +31 -0
  47. torchrec/datasets/criteo.py +831 -0
  48. torchrec/datasets/movielens.py +140 -0
  49. torchrec/datasets/random.py +188 -0
  50. torchrec/datasets/scripts/__init__.py +0 -0
  51. torchrec/datasets/scripts/contiguous_preproc_criteo.py +75 -0
  52. torchrec/datasets/scripts/npy_preproc_criteo.py +73 -0
  53. torchrec/datasets/test_utils/__init__.py +0 -0
  54. torchrec/datasets/test_utils/criteo_test_utils.py +139 -0
  55. torchrec/datasets/utils.py +341 -0
  56. torchrec/distributed/__init__.py +55 -0
  57. torchrec/distributed/batched_embedding_kernel.py +697 -0
  58. torchrec/distributed/collective_utils.py +71 -0
  59. torchrec/distributed/comm.py +149 -0
  60. torchrec/distributed/comm_ops.py +930 -0
  61. torchrec/distributed/dist_data.py +949 -0
  62. torchrec/distributed/embedding.py +638 -0
  63. torchrec/distributed/embedding_kernel.py +326 -0
  64. torchrec/distributed/embedding_lookup.py +760 -0
  65. torchrec/distributed/embedding_sharding.py +660 -0
  66. torchrec/distributed/embedding_tower_sharding.py +992 -0
  67. torchrec/distributed/embedding_types.py +369 -0
  68. torchrec/distributed/embeddingbag.py +731 -0
  69. torchrec/distributed/fused_embeddingbag.py +148 -0
  70. torchrec/distributed/grouped_position_weighted.py +103 -0
  71. torchrec/distributed/model_parallel.py +555 -0
  72. torchrec/distributed/planner/__init__.py +24 -0
  73. torchrec/distributed/planner/constants.py +77 -0
  74. torchrec/distributed/planner/enumerators.py +353 -0
  75. torchrec/distributed/planner/parallelized_planners.py +307 -0
  76. torchrec/distributed/planner/partitioners.py +280 -0
  77. torchrec/distributed/planner/perf_models.py +24 -0
  78. torchrec/distributed/planner/planners.py +290 -0
  79. torchrec/distributed/planner/proposers.py +270 -0
  80. torchrec/distributed/planner/shard_estimators.py +971 -0
  81. torchrec/distributed/planner/stats.py +477 -0
  82. torchrec/distributed/planner/storage_reservations.py +168 -0
  83. torchrec/distributed/planner/types.py +423 -0
  84. torchrec/distributed/planner/utils.py +30 -0
  85. torchrec/distributed/quant_embedding.py +307 -0
  86. torchrec/distributed/quant_embedding_kernel.py +295 -0
  87. torchrec/distributed/quant_embeddingbag.py +288 -0
  88. torchrec/distributed/sharding/__init__.py +0 -0
  89. torchrec/distributed/sharding/cw_sequence_sharding.py +71 -0
  90. torchrec/distributed/sharding/cw_sharding.py +242 -0
  91. torchrec/distributed/sharding/dp_sequence_sharding.py +87 -0
  92. torchrec/distributed/sharding/dp_sharding.py +217 -0
  93. torchrec/distributed/sharding/rw_sequence_sharding.py +130 -0
  94. torchrec/distributed/sharding/rw_sharding.py +393 -0
  95. torchrec/distributed/sharding/sequence_sharding.py +69 -0
  96. torchrec/distributed/sharding/tw_sequence_sharding.py +211 -0
  97. torchrec/distributed/sharding/tw_sharding.py +469 -0
  98. torchrec/distributed/sharding/twcw_sharding.py +32 -0
  99. torchrec/distributed/sharding/twrw_sharding.py +543 -0
  100. torchrec/distributed/sharding/vb_cw_sharding.py +91 -0
  101. torchrec/distributed/sharding/vb_rw_sharding.py +250 -0
  102. torchrec/distributed/sharding/vb_sharding.py +54 -0
  103. torchrec/distributed/sharding/vb_tw_sharding.py +148 -0
  104. torchrec/distributed/sharding/vb_twrw_sharding.py +388 -0
  105. torchrec/distributed/test_utils/__init__.py +0 -0
  106. torchrec/distributed/test_utils/multi_process.py +132 -0
  107. torchrec/distributed/test_utils/test_model.py +818 -0
  108. torchrec/distributed/test_utils/test_model_parallel.py +74 -0
  109. torchrec/distributed/test_utils/test_model_parallel_base.py +117 -0
  110. torchrec/distributed/test_utils/test_sharding.py +280 -0
  111. torchrec/distributed/train_pipeline.py +531 -0
  112. torchrec/distributed/types.py +594 -0
  113. torchrec/distributed/utils.py +186 -0
  114. torchrec/fused_planner.py +57 -0
  115. torchrec/fx/__init__.py +15 -0
  116. torchrec/fx/tracer.py +78 -0
  117. torchrec/inference/__init__.py +25 -0
  118. torchrec/inference/client.py +127 -0
  119. torchrec/inference/model_packager.py +102 -0
  120. torchrec/inference/modules.py +155 -0
  121. torchrec/inference/state_dict_transform.py +103 -0
  122. torchrec/metrics/__init__.py +0 -0
  123. torchrec/metrics/auc.py +159 -0
  124. torchrec/metrics/calibration.py +108 -0
  125. torchrec/metrics/ctr.py +104 -0
  126. torchrec/metrics/metric_module.py +358 -0
  127. torchrec/metrics/metrics_config.py +152 -0
  128. torchrec/metrics/metrics_namespace.py +114 -0
  129. torchrec/metrics/model_utils.py +85 -0
  130. torchrec/metrics/mse.py +134 -0
  131. torchrec/metrics/ne.py +164 -0
  132. torchrec/metrics/rec_metric.py +686 -0
  133. torchrec/metrics/throughput.py +174 -0
  134. torchrec/models/__init__.py +27 -0
  135. torchrec/models/deepfm.py +346 -0
  136. torchrec/models/dlrm.py +708 -0
  137. torchrec/modules/__init__.py +34 -0
  138. torchrec/modules/activation.py +55 -0
  139. torchrec/modules/crossnet.py +446 -0
  140. torchrec/modules/deepfm.py +213 -0
  141. torchrec/modules/embedding_configs.py +148 -0
  142. torchrec/modules/embedding_modules.py +381 -0
  143. torchrec/modules/embedding_tower.py +150 -0
  144. torchrec/modules/feature_processor.py +74 -0
  145. torchrec/modules/fused_embedding_modules.py +625 -0
  146. torchrec/modules/lazy_extension.py +258 -0
  147. torchrec/modules/mlp.py +172 -0
  148. torchrec/modules/utils.py +117 -0
  149. torchrec/optim/__init__.py +35 -0
  150. torchrec/optim/clipping.py +53 -0
  151. torchrec/optim/fused.py +42 -0
  152. torchrec/optim/keyed.py +399 -0
  153. torchrec/optim/rowwise_adagrad.py +222 -0
  154. torchrec/optim/test_utils/__init__.py +19 -0
  155. torchrec/optim/warmup.py +147 -0
  156. torchrec/quant/__init__.py +34 -0
  157. torchrec/quant/embedding_modules.py +545 -0
  158. torchrec/sparse/__init__.py +33 -0
  159. torchrec/sparse/jagged_tensor.py +1281 -0
  160. torchrec/sparse/test_utils/__init__.py +45 -0
  161. torchrec/streamable.py +46 -0
  162. torchrec/test_utils/__init__.py +111 -0
  163. torchrec-0.2.dev0.dist-info/LICENSE +29 -0
  164. torchrec-0.2.dev0.dist-info/METADATA +175 -0
  165. torchrec-0.2.dev0.dist-info/RECORD +167 -0
  166. torchrec-0.2.dev0.dist-info/WHEEL +5 -0
  167. torchrec-0.2.dev0.dist-info/top_level.txt +2 -0
@@ -0,0 +1,74 @@
1
+ #!/usr/bin/env python3
2
+ # Copyright (c) Meta Platforms, Inc. and affiliates.
3
+ # All rights reserved.
4
+ #
5
+ # This source code is licensed under the BSD-style license found in the
6
+ # LICENSE file in the root directory of this source tree.
7
+
8
+ from typing import Dict, List, Optional, Type
9
+
10
+ import torch.distributed as dist # noqa
11
+ import torch.nn as nn
12
+ from fbgemm_gpu.split_embedding_configs import EmbOptimType
13
+ from torchrec.distributed.planner import ParameterConstraints
14
+ from torchrec.distributed.test_utils.multi_process import MultiProcessTestBase
15
+ from torchrec.distributed.test_utils.test_model import TestSparseNN, TestSparseNNBase
16
+ from torchrec.distributed.test_utils.test_sharding import sharding_single_rank_test
17
+ from torchrec.distributed.types import ModuleSharder
18
+ from torchrec.modules.embedding_configs import EmbeddingBagConfig
19
+ from torchrec.test_utils import seed_and_log
20
+
21
+
22
+ class ModelParallelTestShared(MultiProcessTestBase):
23
+ @seed_and_log
24
+ def setUp(self) -> None:
25
+ super().setUp()
26
+
27
+ num_features = 4
28
+ num_weighted_features = 2
29
+
30
+ self.tables = [
31
+ EmbeddingBagConfig(
32
+ num_embeddings=(i + 1) * 10,
33
+ embedding_dim=(i + 2) * 4,
34
+ name="table_" + str(i),
35
+ feature_names=["feature_" + str(i)],
36
+ )
37
+ for i in range(num_features)
38
+ ]
39
+ self.weighted_tables = [
40
+ EmbeddingBagConfig(
41
+ num_embeddings=(i + 1) * 10,
42
+ embedding_dim=(i + 2) * 4,
43
+ name="weighted_table_" + str(i),
44
+ feature_names=["weighted_feature_" + str(i)],
45
+ )
46
+ for i in range(num_weighted_features)
47
+ ]
48
+
49
+ self.embedding_groups = {
50
+ "group_0": ["feature_" + str(i) for i in range(num_features)]
51
+ }
52
+
53
+ def _test_sharding(
54
+ self,
55
+ sharders: List[ModuleSharder[nn.Module]],
56
+ backend: str = "gloo",
57
+ world_size: int = 2,
58
+ local_size: Optional[int] = None,
59
+ constraints: Optional[Dict[str, ParameterConstraints]] = None,
60
+ model_class: Type[TestSparseNNBase] = TestSparseNN,
61
+ ) -> None:
62
+ self._run_multi_process_test(
63
+ callable=sharding_single_rank_test,
64
+ world_size=world_size,
65
+ local_size=local_size,
66
+ model_class=model_class,
67
+ tables=self.tables,
68
+ weighted_tables=self.weighted_tables,
69
+ embedding_groups=self.embedding_groups,
70
+ sharders=sharders,
71
+ backend=backend,
72
+ optim=EmbOptimType.EXACT_SGD,
73
+ constraints=constraints,
74
+ )
@@ -0,0 +1,117 @@
1
+ #!/usr/bin/env python3
2
+ # Copyright (c) Meta Platforms, Inc. and affiliates.
3
+ # All rights reserved.
4
+ #
5
+ # This source code is licensed under the BSD-style license found in the
6
+ # LICENSE file in the root directory of this source tree.
7
+
8
+ import os
9
+ import unittest
10
+ from typing import Callable, cast, Dict, List, Optional
11
+
12
+ import torch
13
+ import torch.nn as nn
14
+ from torchrec.distributed.embedding_types import EmbeddingTableConfig
15
+ from torchrec.distributed.model_parallel import DistributedModelParallel
16
+ from torchrec.distributed.planner import (
17
+ EmbeddingShardingPlanner,
18
+ ParameterConstraints,
19
+ Topology,
20
+ )
21
+ from torchrec.distributed.test_utils.test_model import (
22
+ _get_default_rtol_and_atol,
23
+ TestSparseNNBase,
24
+ )
25
+ from torchrec.distributed.test_utils.test_sharding import (
26
+ copy_state_dict,
27
+ gen_model_and_input,
28
+ )
29
+ from torchrec.distributed.types import ModuleSharder, ShardingEnv, ShardingPlan
30
+ from torchrec.modules.embedding_configs import BaseEmbeddingConfig
31
+ from torchrec.test_utils import seed_and_log
32
+
33
+
34
+ class InferenceModelParallelTestBase(unittest.TestCase):
35
+ @seed_and_log
36
+ def setUp(self) -> None:
37
+ torch.use_deterministic_algorithms(True)
38
+ if torch.cuda.is_available():
39
+ torch.backends.cudnn.allow_tf32 = False
40
+ torch.backends.cuda.matmul.allow_tf32 = False
41
+ os.environ["CUBLAS_WORKSPACE_CONFIG"] = ":4096:8"
42
+
43
+ def tearDown(self) -> None:
44
+ torch.use_deterministic_algorithms(False)
45
+ if torch.cuda.is_available():
46
+ os.unsetenv("CUBLAS_WORKSPACE_CONFIG")
47
+ super().tearDown()
48
+
49
+ def _test_sharded_forward(
50
+ self,
51
+ world_size: int,
52
+ model_class: TestSparseNNBase,
53
+ embedding_groups: Dict[str, List[str]],
54
+ tables: List[EmbeddingTableConfig],
55
+ sharders: List[ModuleSharder[nn.Module]],
56
+ quantize_callable: Callable[[nn.Module], nn.Module],
57
+ weighted_tables: Optional[List[EmbeddingTableConfig]] = None,
58
+ constraints: Optional[Dict[str, ParameterConstraints]] = None,
59
+ ) -> None:
60
+ default_rank = 0
61
+ cuda_device = torch.device(f"cuda:{default_rank}")
62
+ torch.cuda.set_device(cuda_device)
63
+
64
+ # Generate model & inputs.
65
+ (global_model, _inputs) = gen_model_and_input(
66
+ model_class=model_class,
67
+ tables=tables,
68
+ weighted_tables=weighted_tables,
69
+ embedding_groups=embedding_groups,
70
+ world_size=1, # generate only one copy of feature for inference
71
+ num_float_features=16,
72
+ dense_device=cuda_device,
73
+ sparse_device=cuda_device,
74
+ )
75
+ global_model = quantize_callable(global_model)
76
+ local_input = _inputs[0][1][default_rank].to(cuda_device)
77
+
78
+ # Shard model.
79
+ local_model = model_class(
80
+ tables=cast(List[BaseEmbeddingConfig], tables),
81
+ weighted_tables=cast(List[BaseEmbeddingConfig], weighted_tables),
82
+ embedding_groups=embedding_groups,
83
+ dense_device=cuda_device,
84
+ sparse_device=torch.device("meta"),
85
+ num_float_features=16,
86
+ )
87
+ local_model = quantize_callable(local_model)
88
+
89
+ planner = EmbeddingShardingPlanner(
90
+ topology=Topology(world_size, "cuda"),
91
+ constraints=constraints,
92
+ )
93
+ plan: ShardingPlan = planner.plan(local_model, sharders)
94
+
95
+ # Generate a sharded model on a default rank.
96
+ local_model = DistributedModelParallel(
97
+ local_model,
98
+ env=ShardingEnv.from_local(world_size, default_rank),
99
+ plan=plan,
100
+ sharders=sharders,
101
+ init_data_parallel=False,
102
+ )
103
+
104
+ # Load model state from the global model.
105
+ copy_state_dict(local_model.state_dict(), global_model.state_dict())
106
+
107
+ # Run a single training step of the sharded model.
108
+ with torch.inference_mode():
109
+ shard_pred = local_model(local_input)
110
+
111
+ # Run second training step of the unsharded model.
112
+ with torch.inference_mode():
113
+ global_pred = global_model(local_input)
114
+
115
+ # Compare predictions of sharded vs unsharded models.
116
+ rtol, atol = _get_default_rtol_and_atol(global_pred, shard_pred)
117
+ torch.testing.assert_close(global_pred, shard_pred, rtol=rtol, atol=atol)
@@ -0,0 +1,280 @@
1
+ #!/usr/bin/env python3
2
+ # Copyright (c) Meta Platforms, Inc. and affiliates.
3
+ # All rights reserved.
4
+ #
5
+ # This source code is licensed under the BSD-style license found in the
6
+ # LICENSE file in the root directory of this source tree.
7
+
8
+ from enum import Enum
9
+ from typing import Any, cast, Dict, List, Optional, Tuple, Union
10
+
11
+ import torch
12
+ import torch.distributed as dist
13
+ import torch.nn as nn
14
+ from fbgemm_gpu.split_embedding_configs import EmbOptimType
15
+ from torchrec.distributed.embedding_types import EmbeddingTableConfig
16
+ from torchrec.distributed.model_parallel import DistributedModelParallel
17
+ from torchrec.distributed.planner import (
18
+ EmbeddingShardingPlanner,
19
+ ParameterConstraints,
20
+ Topology,
21
+ )
22
+ from torchrec.distributed.test_utils.multi_process import MultiProcessContext
23
+ from torchrec.distributed.test_utils.test_model import (
24
+ ModelInput,
25
+ TestEBCSharder,
26
+ TestEBSharder,
27
+ TestETCSharder,
28
+ TestETSharder,
29
+ TestSparseNNBase,
30
+ )
31
+ from torchrec.distributed.types import (
32
+ ModuleSharder,
33
+ ShardedTensor,
34
+ ShardingEnv,
35
+ ShardingPlan,
36
+ ShardingType,
37
+ )
38
+ from torchrec.modules.embedding_configs import BaseEmbeddingConfig
39
+ from torchrec.optim.keyed import CombinedOptimizer, KeyedOptimizerWrapper
40
+
41
+
42
+ class SharderType(Enum):
43
+ EMBEDDING_BAG = "embedding_bag"
44
+ EMBEDDING_BAG_COLLECTION = "embedding_bag_collection"
45
+ EMBEDDING_TOWER = "embedding_tower"
46
+ EMBEDDING_TOWER_COLLECTION = "embedding_tower_collection"
47
+
48
+
49
+ def create_test_sharder(
50
+ sharder_type: str,
51
+ sharding_type: str,
52
+ kernel_type: str,
53
+ fused_params: Optional[Dict[str, Any]] = None,
54
+ ) -> Union[TestEBSharder, TestEBCSharder, TestETSharder, TestETCSharder]:
55
+ if fused_params is None:
56
+ fused_params = {}
57
+ if "learning_rate" not in fused_params:
58
+ fused_params["learning_rate"] = 0.1
59
+ if sharder_type == SharderType.EMBEDDING_BAG.value:
60
+ return TestEBSharder(sharding_type, kernel_type, fused_params)
61
+ elif sharder_type == SharderType.EMBEDDING_BAG_COLLECTION.value:
62
+ return TestEBCSharder(sharding_type, kernel_type, fused_params)
63
+ elif sharder_type == SharderType.EMBEDDING_TOWER.value:
64
+ return TestETSharder(sharding_type, kernel_type, fused_params)
65
+ elif sharder_type == SharderType.EMBEDDING_TOWER_COLLECTION.value:
66
+ return TestETCSharder(sharding_type, kernel_type, fused_params)
67
+ else:
68
+ raise ValueError(f"Sharder not supported {sharder_type}")
69
+
70
+
71
+ def generate_inputs(
72
+ world_size: int,
73
+ tables: List[EmbeddingTableConfig],
74
+ weighted_tables: Optional[List[EmbeddingTableConfig]] = None,
75
+ batch_size: int = 4,
76
+ num_float_features: int = 16,
77
+ ) -> Tuple[ModelInput, List[ModelInput]]:
78
+ return ModelInput.generate(
79
+ batch_size=batch_size,
80
+ world_size=world_size,
81
+ num_float_features=num_float_features,
82
+ tables=tables,
83
+ weighted_tables=weighted_tables or [],
84
+ )
85
+
86
+
87
+ def gen_model_and_input(
88
+ model_class: TestSparseNNBase,
89
+ tables: List[EmbeddingTableConfig],
90
+ embedding_groups: Dict[str, List[str]],
91
+ world_size: int,
92
+ weighted_tables: Optional[List[EmbeddingTableConfig]] = None,
93
+ num_float_features: int = 16,
94
+ dense_device: Optional[torch.device] = None,
95
+ sparse_device: Optional[torch.device] = None,
96
+ ) -> Tuple[nn.Module, List[Tuple[ModelInput, List[ModelInput]]]]:
97
+ torch.manual_seed(0)
98
+
99
+ model = model_class(
100
+ tables=cast(List[BaseEmbeddingConfig], tables),
101
+ num_float_features=num_float_features,
102
+ weighted_tables=cast(List[BaseEmbeddingConfig], weighted_tables),
103
+ embedding_groups=embedding_groups,
104
+ dense_device=dense_device,
105
+ sparse_device=sparse_device,
106
+ )
107
+ inputs = [
108
+ generate_inputs(
109
+ world_size=world_size,
110
+ tables=tables,
111
+ weighted_tables=weighted_tables,
112
+ num_float_features=num_float_features,
113
+ )
114
+ ]
115
+ return (model, inputs)
116
+
117
+
118
+ def copy_state_dict(
119
+ loc: Dict[str, Union[torch.Tensor, ShardedTensor]],
120
+ glob: Dict[str, torch.Tensor],
121
+ ) -> None:
122
+ for name, tensor in loc.items():
123
+ assert name in glob
124
+ global_tensor = glob[name]
125
+ if isinstance(global_tensor, ShardedTensor):
126
+ global_tensor = global_tensor.local_shards()[0].tensor
127
+ if isinstance(tensor, ShardedTensor):
128
+ for local_shard in tensor.local_shards():
129
+ assert global_tensor.ndim == local_shard.tensor.ndim
130
+ shard_meta = local_shard.metadata
131
+ t = global_tensor.detach()
132
+ if t.ndim == 1:
133
+ t = t[
134
+ shard_meta.shard_offsets[0] : shard_meta.shard_offsets[0]
135
+ + local_shard.tensor.shape[0]
136
+ ]
137
+ elif t.ndim == 2:
138
+ t = t[
139
+ shard_meta.shard_offsets[0] : shard_meta.shard_offsets[0]
140
+ + local_shard.tensor.shape[0],
141
+ shard_meta.shard_offsets[1] : shard_meta.shard_offsets[1]
142
+ + local_shard.tensor.shape[1],
143
+ ]
144
+ else:
145
+ raise ValueError("Tensors with ndim > 2 are not supported")
146
+ local_shard.tensor.copy_(t)
147
+ else:
148
+ tensor.copy_(global_tensor)
149
+
150
+
151
+ def sharding_single_rank_test(
152
+ rank: int,
153
+ world_size: int,
154
+ model_class: TestSparseNNBase,
155
+ embedding_groups: Dict[str, List[str]],
156
+ tables: List[EmbeddingTableConfig],
157
+ sharders: List[ModuleSharder[nn.Module]],
158
+ backend: str,
159
+ optim: EmbOptimType,
160
+ weighted_tables: Optional[List[EmbeddingTableConfig]] = None,
161
+ constraints: Optional[Dict[str, ParameterConstraints]] = None,
162
+ local_size: Optional[int] = None,
163
+ ) -> None:
164
+
165
+ with MultiProcessContext(rank, world_size, backend, local_size) as ctx:
166
+ # Generate model & inputs.
167
+ (global_model, inputs) = gen_model_and_input(
168
+ model_class=model_class,
169
+ tables=tables,
170
+ weighted_tables=weighted_tables,
171
+ embedding_groups=embedding_groups,
172
+ world_size=world_size,
173
+ num_float_features=16,
174
+ )
175
+ global_model = global_model.to(ctx.device)
176
+ global_input = inputs[0][0].to(ctx.device)
177
+ local_input = inputs[0][1][rank].to(ctx.device)
178
+
179
+ # Shard model.
180
+ local_model = model_class(
181
+ tables=cast(List[BaseEmbeddingConfig], tables),
182
+ weighted_tables=cast(List[BaseEmbeddingConfig], weighted_tables),
183
+ embedding_groups=embedding_groups,
184
+ dense_device=ctx.device,
185
+ sparse_device=torch.device("meta"),
186
+ num_float_features=16,
187
+ )
188
+
189
+ planner = EmbeddingShardingPlanner(
190
+ topology=Topology(
191
+ world_size, ctx.device.type, local_world_size=ctx.local_size
192
+ ),
193
+ constraints=constraints,
194
+ )
195
+ plan: ShardingPlan = planner.collective_plan(local_model, sharders, ctx.pg)
196
+ """
197
+ Simulating multiple nodes on a single node. However, metadata information and
198
+ tensor placement must still be consistent. Here we overwrite this to do so.
199
+
200
+ NOTE:
201
+ inter/intra process groups should still behave as expected.
202
+
203
+ TODO: may need to add some checks that only does this if we're running on a
204
+ single GPU (which should be most cases).
205
+ """
206
+
207
+ for group in plan.plan:
208
+ for _, parameter_sharding in plan.plan[group].items():
209
+ if (
210
+ parameter_sharding.sharding_type
211
+ in {
212
+ ShardingType.TABLE_ROW_WISE.value,
213
+ ShardingType.TABLE_COLUMN_WISE.value,
214
+ }
215
+ and ctx.device.type != "cpu"
216
+ ):
217
+ sharding_spec = parameter_sharding.sharding_spec
218
+ if sharding_spec is not None:
219
+ # pyre-ignore
220
+ for shard in sharding_spec.shards:
221
+ placement = shard.placement
222
+ rank: Optional[int] = placement.rank()
223
+ assert rank is not None
224
+ shard.placement = torch.distributed._remote_device(
225
+ f"rank:{rank}/cuda:{rank}"
226
+ )
227
+
228
+ local_model = DistributedModelParallel(
229
+ local_model,
230
+ env=ShardingEnv.from_process_group(ctx.pg),
231
+ plan=plan,
232
+ sharders=sharders,
233
+ device=ctx.device,
234
+ )
235
+
236
+ dense_optim = KeyedOptimizerWrapper(
237
+ dict(local_model.named_parameters()),
238
+ lambda params: torch.optim.SGD(params, lr=0.1),
239
+ )
240
+ local_opt = CombinedOptimizer([local_model.fused_optimizer, dense_optim])
241
+
242
+ # Load model state from the global model.
243
+ copy_state_dict(local_model.state_dict(), global_model.state_dict())
244
+
245
+ # Run a single training step of the sharded model.
246
+ local_pred = gen_full_pred_after_one_step(local_model, local_opt, local_input)
247
+
248
+ all_local_pred = []
249
+ for _ in range(world_size):
250
+ all_local_pred.append(torch.empty_like(local_pred))
251
+ dist.all_gather(all_local_pred, local_pred, group=ctx.pg)
252
+
253
+ # Run second training step of the unsharded model.
254
+ assert optim == EmbOptimType.EXACT_SGD
255
+ global_opt = torch.optim.SGD(global_model.parameters(), lr=0.1)
256
+ global_pred = gen_full_pred_after_one_step(
257
+ global_model, global_opt, global_input
258
+ )
259
+
260
+ # Compare predictions of sharded vs unsharded models.
261
+ torch.testing.assert_allclose(global_pred, torch.cat(all_local_pred))
262
+
263
+
264
+ def gen_full_pred_after_one_step(
265
+ model: nn.Module,
266
+ opt: torch.optim.Optimizer,
267
+ input: ModelInput,
268
+ ) -> torch.Tensor:
269
+ # Run a single training step of the global model.
270
+ opt.zero_grad()
271
+ model.train(True)
272
+ loss, _ = model(input)
273
+ loss.backward()
274
+ opt.step()
275
+
276
+ # Run a forward pass of the global model.
277
+ with torch.no_grad():
278
+ model.train(False)
279
+ full_pred = model(input)
280
+ return full_pred