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,186 @@
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 collections import OrderedDict
9
+ from typing import Any, Dict, List, Optional, Set, Union
10
+
11
+ import torch
12
+ from torchrec.distributed.types import ShardedModule
13
+
14
+
15
+ def append_prefix(prefix: str, name: str) -> str:
16
+ """
17
+ Appends provided prefix to provided name.
18
+ """
19
+
20
+ if prefix != "" and name != "":
21
+ return prefix + "." + name
22
+ else:
23
+ return prefix + name
24
+
25
+
26
+ def filter_state_dict(
27
+ state_dict: "OrderedDict[str, torch.Tensor]", name: str
28
+ ) -> "OrderedDict[str, torch.Tensor]":
29
+ """
30
+ Filters state dict for keys that start with provided name.
31
+ Strips provided name from beginning of key in the resulting state dict.
32
+
33
+ Args:
34
+ state_dict (OrderedDict[str, torch.Tensor]): input state dict to filter.
35
+ name (str): name to filter from state dict keys.
36
+
37
+ Returns:
38
+ OrderedDict[str, torch.Tensor]: filtered state dict.
39
+ """
40
+
41
+ filtered_state_dict = OrderedDict()
42
+ for key, value in state_dict.items():
43
+ if key.startswith(name):
44
+ # + 1 to length is to remove the '.' after the key
45
+ filtered_state_dict[key[len(name) + 1 :]] = value
46
+ return filtered_state_dict
47
+
48
+
49
+ def add_prefix_to_state_dict(state_dict: Dict[str, Any], prefix: str) -> None:
50
+ """
51
+ Adds prefix to all keys in state dict, in place.
52
+
53
+ Args:
54
+ state_dict (Dict[str, Any]): input state dict to update.
55
+ prefix (str): name to filter from state dict keys.
56
+
57
+ Returns:
58
+ None.
59
+ """
60
+ keys = sorted(state_dict.keys())
61
+ for key in keys:
62
+ state_dict[prefix + key] = state_dict.pop(key)
63
+
64
+ if "_metadata" in state_dict:
65
+ metadata = state_dict["_metadata"]
66
+ for key in list(metadata.keys()):
67
+ if len(key) == 0:
68
+ continue
69
+ metadata[prefix + key] = metadata.pop(key)
70
+
71
+
72
+ def _get_unsharded_module_names_helper(
73
+ model: torch.nn.Module,
74
+ path: str,
75
+ unsharded_module_names: Set[str],
76
+ ) -> bool:
77
+ sharded_children = set()
78
+ for name, child in model.named_children():
79
+ curr_path = path + name
80
+ if isinstance(child, ShardedModule):
81
+ sharded_children.add(name)
82
+ else:
83
+ child_sharded = _get_unsharded_module_names_helper(
84
+ child,
85
+ curr_path + ".",
86
+ unsharded_module_names,
87
+ )
88
+ if child_sharded:
89
+ sharded_children.add(name)
90
+
91
+ if len(sharded_children) > 0:
92
+ for name, _ in model.named_children():
93
+ if name not in sharded_children:
94
+ unsharded_module_names.add(path + name)
95
+
96
+ return len(sharded_children) > 0
97
+
98
+
99
+ def get_unsharded_module_names(model: torch.nn.Module) -> List[str]:
100
+ """
101
+ Retrieves names of top level modules that do not contain any sharded sub-modules.
102
+
103
+ Args:
104
+ model (torch.nn.Module): model to retrieve unsharded module names from.
105
+
106
+ Returns:
107
+ List[str]: list of names of modules that don't have sharded sub-modules.
108
+ """
109
+
110
+ unsharded_module_names: Set[str] = set()
111
+ _get_unsharded_module_names_helper(
112
+ model,
113
+ "",
114
+ unsharded_module_names,
115
+ )
116
+ return list(unsharded_module_names)
117
+
118
+
119
+ class sharded_model_copy:
120
+ """
121
+ Allows copying of DistributedModelParallel module to a target device.
122
+
123
+ Example::
124
+
125
+ # Copying model to CPU.
126
+
127
+ m = DistributedModelParallel(m)
128
+ with sharded_model_copy("cpu"):
129
+ m_cpu = copy.deepcopy(m)
130
+ """
131
+
132
+ def __init__(self, device: Optional[Union[str, int, torch.device]]) -> None:
133
+ self.device = device
134
+
135
+ def __enter__(self) -> None:
136
+ # pyre-ignore [16]
137
+ self.t_copy_save_ = torch.Tensor.__deepcopy__
138
+ # pyre-ignore [16]
139
+ self.p_copy_save_ = torch.nn.Parameter.__deepcopy__
140
+
141
+ device = self.device
142
+
143
+ # pyre-ignore [2, 3, 53]
144
+ def _tensor_copy(tensor, memo):
145
+ if tensor.device != device:
146
+ return tensor.detach().to(device)
147
+ else:
148
+ return tensor.detach().clone()
149
+
150
+ # pyre-ignore [2, 3]
151
+ def _no_copy(obj, memo):
152
+ return obj
153
+
154
+ _copy_or_not = _tensor_copy if self.device is not None else _no_copy
155
+
156
+ # pyre-ignore [2, 3, 53]
157
+ def _param_copy(param, memo):
158
+ return torch.nn.Parameter(
159
+ _copy_or_not(param, memo), requires_grad=param.requires_grad
160
+ )
161
+
162
+ torch.Tensor.__deepcopy__ = _copy_or_not
163
+ torch.nn.Parameter.__deepcopy__ = _param_copy
164
+ # pyre-fixme[16]: `Type` has no attribute `__deepcopy__`.
165
+ torch._C._distributed_c10d.ProcessGroupNCCL.__deepcopy__ = _no_copy
166
+ # pyre-fixme[16]: `Type` has no attribute `__deepcopy__`.
167
+ torch._C._distributed_c10d.ProcessGroupGloo.__deepcopy__ = _no_copy
168
+ # pyre-fixme[16]: `Type` has no attribute `__deepcopy__`.
169
+ torch._C._distributed_c10d.Work.__deepcopy__ = _no_copy
170
+ # pyre-ignore [16]
171
+ torch.cuda.streams.Stream.__deepcopy__ = _no_copy
172
+
173
+ # pyre-ignore [2]
174
+ def __exit__(self, exc_type, exc_val, exc_tb) -> None:
175
+ # pyre-ignore [16]
176
+ torch.Tensor.__deepcopy__ = self.t_copy_save_
177
+ # pyre-ignore [16]
178
+ torch.nn.Parameter.__deepcopy__ = self.p_copy_save_
179
+ # pyre-fixme[16]: `Type` has no attribute `__deepcopy__`.
180
+ torch._C._distributed_c10d.ProcessGroupNCCL.__deepcopy__ = None
181
+ # pyre-fixme[16]: `Type` has no attribute `__deepcopy__`.
182
+ torch._C._distributed_c10d.ProcessGroupGloo.__deepcopy__ = None
183
+ # pyre-fixme[16]: `Type` has no attribute `__deepcopy__`.
184
+ torch._C._distributed_c10d.Work.__deepcopy__ = None
185
+ # pyre-ignore [16]
186
+ torch.cuda.streams.Stream.__deepcopy__ = None
@@ -0,0 +1,57 @@
1
+ from torchrec.modules.embedding_configs import (
2
+ DataType,
3
+ EmbeddingBagConfig,
4
+ EmbeddingConfig,
5
+ )
6
+ from torchrec.modules.embedding_modules import (
7
+ EmbeddingBagCollection,
8
+ )
9
+ import torchrec
10
+ import torch
11
+ from torchrec.models.dlrm import DLRM, DLRMTrain
12
+ from torchrec.distributed.fused_embeddingbag import FusedEmbeddingBagCollectionSharder
13
+ from torchrec.modules.fused_embedding_modules import fuse_embedding_optimizer
14
+
15
+ eb1_config = EmbeddingBagConfig(
16
+ name="t1",
17
+ embedding_dim=16,
18
+ num_embeddings=1000000000,
19
+ feature_names=["f1"],
20
+ )
21
+ embedding_bag_collection = EmbeddingBagCollection(
22
+ tables=[eb1_config],
23
+ device=torch.device("meta"),
24
+ )
25
+ device=torch.device("cuda")
26
+ dlrm_model = DLRM(
27
+ embedding_bag_collection,
28
+ dense_in_features=1024,
29
+ dense_arch_layer_sizes=[512, 256, 16],
30
+ over_arch_layer_sizes=[512, 512, 256, 1],
31
+ dense_device=device,
32
+ )
33
+
34
+ model = DLRMTrain(dlrm_model)
35
+ model = fuse_embedding_optimizer(
36
+ model,
37
+ optimizer_type=torchrec.optim.RowWiseAdagrad,
38
+ optimizer_kwargs={
39
+ "lr": 0.02,
40
+ "eps": 0.002,
41
+ },
42
+ device=torch.device("meta"),
43
+ )
44
+
45
+ from torchrec.distributed.planner import (
46
+ EmbeddingShardingPlanner,
47
+ Topology,
48
+ )
49
+ planner = EmbeddingShardingPlanner(
50
+ topology=Topology(
51
+ local_world_size=8,
52
+ world_size=8,
53
+ compute_device="cuda",
54
+ )
55
+ )
56
+ plan = planner.plan(model, [FusedEmbeddingBagCollectionSharder()])
57
+ print(plan)
@@ -0,0 +1,15 @@
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
+ """Torchrec Tracer
9
+
10
+ Custom FX tracer for torchrec
11
+
12
+ See `Torch.FX documentation <https://pytorch.org/docs/stable/fx.html>`_
13
+ """
14
+
15
+ from torchrec.fx.tracer import symbolic_trace, Tracer # noqa
torchrec/fx/tracer.py ADDED
@@ -0,0 +1,78 @@
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 Any, Callable, Dict, Optional, Union
9
+
10
+ import torch
11
+ from torch.fx.node import Argument
12
+ from torchrec.distributed.types import NoWait
13
+
14
+
15
+ class Tracer(torch.fx.Tracer):
16
+ """
17
+ Custom FX tracer for torchrec
18
+
19
+ See `Torch.FX documentation <https://pytorch.org/docs/stable/fx.html>`_
20
+
21
+ We create a custom FX tracer to trace torchrec based models. The custom tracer
22
+ handles python generic types (i.e. NoWait[T], Awaitable[T]) and lower it to
23
+ TorchScript if needed
24
+ """
25
+
26
+ def __init__(self) -> None:
27
+ super().__init__()
28
+
29
+ # pyre-ignore[2]
30
+ def create_arg(self, a: Any) -> Argument:
31
+ """
32
+ A method to specify the behavior of tracing when preparing values to
33
+ be used as arguments to nodes in the ``Graph``.
34
+
35
+ Adds support for the NoWait type in addition to the default tracer
36
+
37
+ Args:
38
+ a (Any): The value to be emitted as an ``Argument`` in the ``Graph``.
39
+
40
+ Returns:
41
+ Argument: The value ``a`` converted into the appropriate ``Argument``
42
+ """
43
+ if isinstance(a, NoWait):
44
+ return self.create_node(
45
+ "call_function",
46
+ target=NoWait,
47
+ args=self.create_arg((a._obj,)),
48
+ kwargs={},
49
+ type_expr=NoWait,
50
+ )
51
+ return super().create_arg(a)
52
+
53
+
54
+ def symbolic_trace(
55
+ # pyre-ignore[24]
56
+ root: Union[torch.nn.Module, Callable],
57
+ concrete_args: Optional[Dict[str, Any]] = None,
58
+ ) -> torch.fx.GraphModule:
59
+ """
60
+ Symbolic tracing API
61
+
62
+ Given an ``nn.Module`` or function instance ``root``, this function will return a ``GraphModule``
63
+ constructed by recording operations seen while tracing through ``root``.
64
+
65
+ ``concrete_args`` allows you to partially specialize your function, whether it's to remove control flow or data structures.
66
+
67
+ Args:
68
+ root (Union[torch.nn.Module, Callable]): Module or function to be traced and converted
69
+ into a Graph representation.
70
+ concrete_args (Optional[Dict[str, any]]): Inputs to be partially specialized
71
+
72
+ Returns:
73
+ GraphModule: a Module created from the recorded operations from ``root``.
74
+ """
75
+
76
+ tracer = Tracer()
77
+ graph = tracer.trace(root, concrete_args)
78
+ return torch.fx.GraphModule(root, graph)
@@ -0,0 +1,25 @@
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
+ """Torchrec Inference
9
+
10
+ Torchrec inference provides a Torch.Deploy based library for GPU inference.
11
+
12
+ These includes:
13
+ - Model packaging in Python
14
+ - `PredictModule` and `PredictFactory` are the contracts between the Python model authoring and the C++ model serving.
15
+ - `PredictFactoryPackager` can be used to package a PredictFactory class using torch.package.
16
+ - Model serving in C++
17
+ - `BatchingQueue` is a generalized config-based request tensor batching implementation.
18
+ - `GPUExecutor` handles the forward call into the inference model inside Torch.Deploy.
19
+
20
+ We implemented an example of how to use this library with the TorchRec DLRM model.
21
+ - `examples/dlrm/inference/dlrm_packager.py`: this demonstrates how to export the DLRM model as a torch.package.
22
+ - `examples/dlrm/inference/dlrm_predict.py`: this shows how to use `PredictModule` and `PredictFactory` based on an existing model.
23
+ """
24
+
25
+ from . import model_packager, modules # noqa # noqa
@@ -0,0 +1,127 @@
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 argparse
9
+ import logging
10
+ import os
11
+
12
+ import grpc
13
+ import torch
14
+ from gen.torchrec.inference import predictor_pb2, predictor_pb2_grpc
15
+ from torch.utils.data import DataLoader
16
+ from torchrec.datasets.criteo import DEFAULT_CAT_NAMES, DEFAULT_INT_NAMES
17
+ from torchrec.datasets.random import RandomRecDataset
18
+ from torchrec.datasets.utils import Batch
19
+
20
+
21
+ def create_training_batch(args: argparse.Namespace) -> Batch:
22
+ return next(
23
+ iter(
24
+ DataLoader(
25
+ RandomRecDataset(
26
+ keys=DEFAULT_CAT_NAMES,
27
+ batch_size=args.batch_size,
28
+ hash_size=args.num_embedding_features,
29
+ ids_per_feature=1,
30
+ num_dense=len(DEFAULT_INT_NAMES),
31
+ ),
32
+ batch_sampler=None,
33
+ pin_memory=False,
34
+ num_workers=0,
35
+ )
36
+ )
37
+ )
38
+
39
+
40
+ def create_request(
41
+ batch: Batch, args: argparse.Namespace
42
+ ) -> predictor_pb2.PredictionRequest:
43
+ def to_bytes(tensor: torch.Tensor) -> bytes:
44
+ return tensor.cpu().numpy().tobytes()
45
+
46
+ float_features = predictor_pb2.FloatFeatures(
47
+ num_features=args.num_float_features,
48
+ values=to_bytes(batch.dense_features),
49
+ )
50
+
51
+ id_list_features = predictor_pb2.SparseFeatures(
52
+ num_features=args.num_id_list_features,
53
+ values=to_bytes(batch.sparse_features.values()),
54
+ lengths=to_bytes(batch.sparse_features.lengths()),
55
+ )
56
+
57
+ id_score_list_features = predictor_pb2.SparseFeatures(num_features=0)
58
+ embedding_features = predictor_pb2.FloatFeatures(num_features=0)
59
+ unary_features = predictor_pb2.SparseFeatures(num_features=0)
60
+
61
+ return predictor_pb2.PredictionRequest(
62
+ batch_size=args.batch_size,
63
+ float_features=float_features,
64
+ id_list_features=id_list_features,
65
+ id_score_list_features=id_score_list_features,
66
+ embedding_features=embedding_features,
67
+ unary_features=unary_features,
68
+ )
69
+
70
+
71
+ if __name__ == "__main__":
72
+ logging.basicConfig(level=logging.DEBUG)
73
+
74
+ parser = argparse.ArgumentParser()
75
+ parser.add_argument(
76
+ "--ip",
77
+ type=str,
78
+ default="0.0.0.0",
79
+ )
80
+ parser.add_argument(
81
+ "--port",
82
+ type=int,
83
+ default=50051,
84
+ )
85
+ parser.add_argument(
86
+ "--num_float_features",
87
+ type=int,
88
+ default=13,
89
+ )
90
+ parser.add_argument(
91
+ "--num_id_list_features",
92
+ type=int,
93
+ default=26,
94
+ )
95
+ parser.add_argument(
96
+ "--num_id_score_list_features",
97
+ type=int,
98
+ default=0,
99
+ )
100
+ parser.add_argument(
101
+ "--num_embedding_features",
102
+ type=int,
103
+ default=100000,
104
+ )
105
+ parser.add_argument(
106
+ "--embedding_feature_dim",
107
+ type=int,
108
+ default=100,
109
+ )
110
+ parser.add_argument(
111
+ "--batch_size",
112
+ type=int,
113
+ default=100,
114
+ )
115
+
116
+ args: argparse.Namespace = parser.parse_args()
117
+
118
+ training_batch: Batch = create_training_batch(args)
119
+ request: predictor_pb2.PredictionRequest = create_request(training_batch, args)
120
+
121
+ with grpc.insecure_channel(f"{args.ip}:{args.port}") as channel:
122
+ stub = predictor_pb2_grpc.PredictorStub(channel)
123
+ response = stub.Predict(request)
124
+ print("Response: ", response.predictions["default"].data)
125
+
126
+ if __name__ == "__main__":
127
+ logging.basicConfig()
@@ -0,0 +1,102 @@
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 abc
9
+ from pathlib import Path
10
+ from typing import Any, BinaryIO, Dict, Type, TypeVar, Union
11
+
12
+ from torch.package import PackageExporter
13
+ from torchrec.inference.modules import PredictFactory
14
+
15
+ LOADER_MODULE = "__module_loader"
16
+ LOADER_FACTORY = "MODULE_FACTORY"
17
+ LOADER_CODE = f"""
18
+ import %PACKAGE%
19
+
20
+ {LOADER_FACTORY}=%PACKAGE%.%CLASS%
21
+ """
22
+ CONFIG_MODULE = "__configs"
23
+
24
+ T = TypeVar("T")
25
+
26
+
27
+ try:
28
+ # pyre-fixme[21]: Could not find module `torch_package_importer`.
29
+ import torch_package_importer # @manual
30
+ except ImportError:
31
+ pass
32
+
33
+
34
+ def load_config_text(name: str) -> str:
35
+ return torch_package_importer.load_text("__configs", name)
36
+
37
+
38
+ def load_pickle_config(name: str, clazz: Type[T]) -> T:
39
+ loaded_obj = torch_package_importer.load_pickle("__configs", name)
40
+ assert isinstance(
41
+ loaded_obj, clazz
42
+ ), f"The loaded config {type(loaded_obj)} is not of type {clazz}"
43
+ return loaded_obj
44
+
45
+
46
+ class PredictFactoryPackager:
47
+ @classmethod
48
+ @abc.abstractclassmethod
49
+ def set_extern_modules(cls, pe: PackageExporter) -> None:
50
+ pass
51
+
52
+ @classmethod
53
+ @abc.abstractclassmethod
54
+ def set_mocked_modules(cls, pe: PackageExporter) -> None:
55
+ pass
56
+
57
+ @classmethod
58
+ def save_predict_factory(
59
+ cls,
60
+ predict_factory: Type[PredictFactory],
61
+ configs: Dict[str, Any],
62
+ output: Union[str, Path, BinaryIO],
63
+ extra_files: Dict[str, str],
64
+ loader_code: str = LOADER_CODE,
65
+ ) -> None:
66
+ with PackageExporter(output) as pe:
67
+ # pyre-fixme[29]: `BoundMethod[abc.abstractclassmethod[None],
68
+ # Type[PredictFactoryPackager]]` is not a function.
69
+ cls.set_extern_modules(pe)
70
+ # pyre-fixme[29]: `BoundMethod[abc.abstractclassmethod[None],
71
+ # Type[PredictFactoryPackager]]` is not a function.
72
+ cls.set_mocked_modules(pe)
73
+ pe.intern("**")
74
+ for k, v in extra_files.items():
75
+ pe.save_text("extra_files", k, v)
76
+ cls._save_predict_factory(
77
+ pe, predict_factory, configs, loader_code=loader_code
78
+ )
79
+
80
+ @classmethod
81
+ def _save_predict_factory(
82
+ cls,
83
+ pe: PackageExporter,
84
+ predict_factory: Type[PredictFactory],
85
+ configs: Dict[str, Any],
86
+ loader_code: str = LOADER_CODE,
87
+ ) -> None:
88
+ # Save loader entry point.
89
+ code = loader_code.replace("%PACKAGE%", predict_factory.__module__).replace(
90
+ "%CLASS%", predict_factory.__name__
91
+ )
92
+ pe.save_source_string(module_name=LOADER_MODULE, src=code)
93
+
94
+ # Save configs
95
+ for name, config in configs.items():
96
+ if isinstance(config, str):
97
+ pe.save_text(CONFIG_MODULE, name, config)
98
+ else:
99
+ pe.save_pickle(CONFIG_MODULE, name, config)
100
+
101
+ # Save predict factory.
102
+ pe.save_module(predict_factory.__module__)