nvidia-modelopt 0.27.0__py3-none-win_amd64.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 (242) hide show
  1. modelopt/__init__.py +42 -0
  2. modelopt/deploy/__init__.py +16 -0
  3. modelopt/deploy/llm/__init__.py +33 -0
  4. modelopt/deploy/llm/generate.py +297 -0
  5. modelopt/deploy/llm/nemo_utils.py +184 -0
  6. modelopt/onnx/__init__.py +35 -0
  7. modelopt/onnx/op_types.py +300 -0
  8. modelopt/onnx/quantization/__init__.py +20 -0
  9. modelopt/onnx/quantization/__main__.py +252 -0
  10. modelopt/onnx/quantization/calib_utils.py +151 -0
  11. modelopt/onnx/quantization/extensions.py +34 -0
  12. modelopt/onnx/quantization/fp8.py +336 -0
  13. modelopt/onnx/quantization/graph_utils.py +1257 -0
  14. modelopt/onnx/quantization/gs_patching.py +112 -0
  15. modelopt/onnx/quantization/int4.py +1326 -0
  16. modelopt/onnx/quantization/int8.py +270 -0
  17. modelopt/onnx/quantization/operators.py +96 -0
  18. modelopt/onnx/quantization/ort_patching.py +791 -0
  19. modelopt/onnx/quantization/ort_utils.py +258 -0
  20. modelopt/onnx/quantization/partitioning.py +411 -0
  21. modelopt/onnx/quantization/qdq_utils.py +826 -0
  22. modelopt/onnx/quantization/quant_utils.py +174 -0
  23. modelopt/onnx/quantization/quantize.py +430 -0
  24. modelopt/onnx/quantization/src/modelopt_round_and_pack_ext.cpp +127 -0
  25. modelopt/onnx/quantization/trt_utils.py +206 -0
  26. modelopt/onnx/utils.py +646 -0
  27. modelopt/torch/__init__.py +31 -0
  28. modelopt/torch/_deploy/__init__.py +23 -0
  29. modelopt/torch/_deploy/_runtime/__init__.py +30 -0
  30. modelopt/torch/_deploy/_runtime/common.py +73 -0
  31. modelopt/torch/_deploy/_runtime/ort_client.py +192 -0
  32. modelopt/torch/_deploy/_runtime/registry.py +83 -0
  33. modelopt/torch/_deploy/_runtime/runtime_client.py +158 -0
  34. modelopt/torch/_deploy/_runtime/tensorrt/constants.py +107 -0
  35. modelopt/torch/_deploy/_runtime/tensorrt/engine_builder.py +336 -0
  36. modelopt/torch/_deploy/_runtime/tensorrt/hw_param_config.py +51 -0
  37. modelopt/torch/_deploy/_runtime/tensorrt/layerwise_profiling.py +175 -0
  38. modelopt/torch/_deploy/_runtime/tensorrt/parse_trtexec_log.py +154 -0
  39. modelopt/torch/_deploy/_runtime/tensorrt/tensorrt_utils.py +198 -0
  40. modelopt/torch/_deploy/_runtime/trt_client.py +218 -0
  41. modelopt/torch/_deploy/compilation.py +144 -0
  42. modelopt/torch/_deploy/device_model.py +157 -0
  43. modelopt/torch/_deploy/profiling.py +197 -0
  44. modelopt/torch/_deploy/utils/__init__.py +18 -0
  45. modelopt/torch/_deploy/utils/onnx_optimizer.py +118 -0
  46. modelopt/torch/_deploy/utils/onnx_utils.py +58 -0
  47. modelopt/torch/_deploy/utils/torch_onnx.py +512 -0
  48. modelopt/torch/distill/__init__.py +28 -0
  49. modelopt/torch/distill/config.py +130 -0
  50. modelopt/torch/distill/distillation.py +84 -0
  51. modelopt/torch/distill/distillation_model.py +317 -0
  52. modelopt/torch/distill/loss_balancers.py +139 -0
  53. modelopt/torch/distill/losses.py +150 -0
  54. modelopt/torch/distill/mode.py +224 -0
  55. modelopt/torch/distill/plugins/__init__.py +21 -0
  56. modelopt/torch/distill/plugins/megatron.py +477 -0
  57. modelopt/torch/distill/registry.py +23 -0
  58. modelopt/torch/export/__init__.py +23 -0
  59. modelopt/torch/export/distribute.py +303 -0
  60. modelopt/torch/export/hf_config_map.py +84 -0
  61. modelopt/torch/export/layer_utils.py +1716 -0
  62. modelopt/torch/export/mcore_config_map.py +25 -0
  63. modelopt/torch/export/mcore_hf_export_map.py +496 -0
  64. modelopt/torch/export/model_config.py +616 -0
  65. modelopt/torch/export/model_config_export.py +556 -0
  66. modelopt/torch/export/model_config_utils.py +392 -0
  67. modelopt/torch/export/model_utils.py +68 -0
  68. modelopt/torch/export/postprocess.py +848 -0
  69. modelopt/torch/export/quant_utils.py +990 -0
  70. modelopt/torch/export/tensorrt_llm_type.py +42 -0
  71. modelopt/torch/export/tensorrt_llm_utils.py +403 -0
  72. modelopt/torch/export/transformer_engine.py +94 -0
  73. modelopt/torch/export/unified_export_hf.py +339 -0
  74. modelopt/torch/export/unified_export_megatron.py +1205 -0
  75. modelopt/torch/nas/__init__.py +27 -0
  76. modelopt/torch/nas/_algorithms.py +430 -0
  77. modelopt/torch/nas/_patch.py +262 -0
  78. modelopt/torch/nas/algorithms.py +452 -0
  79. modelopt/torch/nas/autonas.py +637 -0
  80. modelopt/torch/nas/config.py +94 -0
  81. modelopt/torch/nas/conversion.py +119 -0
  82. modelopt/torch/nas/hparams/__init__.py +19 -0
  83. modelopt/torch/nas/hparams/concat.py +281 -0
  84. modelopt/torch/nas/hparams/container.py +48 -0
  85. modelopt/torch/nas/mode.py +135 -0
  86. modelopt/torch/nas/modules/__init__.py +21 -0
  87. modelopt/torch/nas/modules/container.py +98 -0
  88. modelopt/torch/nas/modules/conv.py +253 -0
  89. modelopt/torch/nas/modules/linear.py +79 -0
  90. modelopt/torch/nas/modules/norm.py +198 -0
  91. modelopt/torch/nas/modules/utils.py +63 -0
  92. modelopt/torch/nas/plugins/__init__.py +29 -0
  93. modelopt/torch/nas/plugins/megatron.py +1038 -0
  94. modelopt/torch/nas/plugins/torch.py +71 -0
  95. modelopt/torch/nas/plugins/transformer_engine.py +42 -0
  96. modelopt/torch/nas/plugins/transformers.py +207 -0
  97. modelopt/torch/nas/registry.py +23 -0
  98. modelopt/torch/nas/search_space.py +245 -0
  99. modelopt/torch/nas/traced_hp.py +149 -0
  100. modelopt/torch/nas/utils.py +406 -0
  101. modelopt/torch/opt/__init__.py +43 -0
  102. modelopt/torch/opt/_hooks.py +104 -0
  103. modelopt/torch/opt/config.py +396 -0
  104. modelopt/torch/opt/conversion.py +609 -0
  105. modelopt/torch/opt/dynamic.py +1295 -0
  106. modelopt/torch/opt/hparam.py +261 -0
  107. modelopt/torch/opt/mode.py +322 -0
  108. modelopt/torch/opt/plugins/__init__.py +35 -0
  109. modelopt/torch/opt/plugins/diffusers.py +24 -0
  110. modelopt/torch/opt/plugins/huggingface.py +195 -0
  111. modelopt/torch/opt/plugins/mcore_dist_checkpointing.py +685 -0
  112. modelopt/torch/opt/plugins/megatron.py +45 -0
  113. modelopt/torch/opt/plugins/peft.py +102 -0
  114. modelopt/torch/opt/plugins/transformers.py +24 -0
  115. modelopt/torch/opt/searcher.py +364 -0
  116. modelopt/torch/opt/utils.py +77 -0
  117. modelopt/torch/prune/__init__.py +26 -0
  118. modelopt/torch/prune/config.py +86 -0
  119. modelopt/torch/prune/fastnas.py +263 -0
  120. modelopt/torch/prune/gradnas.py +313 -0
  121. modelopt/torch/prune/mcore_gpt_minitron.py +165 -0
  122. modelopt/torch/prune/mode.py +146 -0
  123. modelopt/torch/prune/plugins/__init__.py +24 -0
  124. modelopt/torch/prune/plugins/megatron.py +32 -0
  125. modelopt/torch/prune/plugins/transformers.py +40 -0
  126. modelopt/torch/prune/pruning.py +211 -0
  127. modelopt/torch/quantization/__init__.py +26 -0
  128. modelopt/torch/quantization/calib/__init__.py +25 -0
  129. modelopt/torch/quantization/calib/bias.py +160 -0
  130. modelopt/torch/quantization/calib/calibrator.py +63 -0
  131. modelopt/torch/quantization/calib/histogram.py +437 -0
  132. modelopt/torch/quantization/calib/max.py +114 -0
  133. modelopt/torch/quantization/compress.py +88 -0
  134. modelopt/torch/quantization/config.py +876 -0
  135. modelopt/torch/quantization/conversion.py +337 -0
  136. modelopt/torch/quantization/export_onnx.py +544 -0
  137. modelopt/torch/quantization/extensions.py +89 -0
  138. modelopt/torch/quantization/mode.py +122 -0
  139. modelopt/torch/quantization/model_calib.py +907 -0
  140. modelopt/torch/quantization/model_quant.py +460 -0
  141. modelopt/torch/quantization/nn/__init__.py +26 -0
  142. modelopt/torch/quantization/nn/functional.py +112 -0
  143. modelopt/torch/quantization/nn/modules/__init__.py +16 -0
  144. modelopt/torch/quantization/nn/modules/quant_activations.py +22 -0
  145. modelopt/torch/quantization/nn/modules/quant_batchnorm.py +24 -0
  146. modelopt/torch/quantization/nn/modules/quant_conv.py +123 -0
  147. modelopt/torch/quantization/nn/modules/quant_instancenorm.py +45 -0
  148. modelopt/torch/quantization/nn/modules/quant_linear.py +50 -0
  149. modelopt/torch/quantization/nn/modules/quant_module.py +193 -0
  150. modelopt/torch/quantization/nn/modules/quant_pooling.py +117 -0
  151. modelopt/torch/quantization/nn/modules/quant_rnn.py +532 -0
  152. modelopt/torch/quantization/nn/modules/tensor_quantizer.py +1265 -0
  153. modelopt/torch/quantization/optim.py +38 -0
  154. modelopt/torch/quantization/plugins/__init__.py +59 -0
  155. modelopt/torch/quantization/plugins/apex.py +54 -0
  156. modelopt/torch/quantization/plugins/attention.py +395 -0
  157. modelopt/torch/quantization/plugins/custom.py +120 -0
  158. modelopt/torch/quantization/plugins/diffusers.py +237 -0
  159. modelopt/torch/quantization/plugins/fairscale.py +44 -0
  160. modelopt/torch/quantization/plugins/huggingface.py +311 -0
  161. modelopt/torch/quantization/plugins/megatron.py +377 -0
  162. modelopt/torch/quantization/plugins/nemo.py +67 -0
  163. modelopt/torch/quantization/plugins/peft.py +56 -0
  164. modelopt/torch/quantization/plugins/transformer_engine.py +60 -0
  165. modelopt/torch/quantization/qtensor/__init__.py +23 -0
  166. modelopt/torch/quantization/qtensor/base_qtensor.py +162 -0
  167. modelopt/torch/quantization/qtensor/fp8_tensor.py +143 -0
  168. modelopt/torch/quantization/qtensor/int4_tensor.py +123 -0
  169. modelopt/torch/quantization/qtensor/nf4_tensor.py +192 -0
  170. modelopt/torch/quantization/quant_modules.py +50 -0
  171. modelopt/torch/quantization/src/tensor_quant.cpp +77 -0
  172. modelopt/torch/quantization/src/tensor_quant.h +69 -0
  173. modelopt/torch/quantization/src/tensor_quant_fp8.cpp +48 -0
  174. modelopt/torch/quantization/src/tensor_quant_gpu.cu +361 -0
  175. modelopt/torch/quantization/src/tensor_quant_gpu_fp8.cu +122 -0
  176. modelopt/torch/quantization/src/tensor_quant_mx.cu +401 -0
  177. modelopt/torch/quantization/src/tensor_quant_mx.h +247 -0
  178. modelopt/torch/quantization/tensor_quant.py +734 -0
  179. modelopt/torch/quantization/triton/__init__.py +36 -0
  180. modelopt/torch/quantization/triton/fp4_kernel.py +156 -0
  181. modelopt/torch/quantization/utils.py +277 -0
  182. modelopt/torch/sparsity/__init__.py +19 -0
  183. modelopt/torch/sparsity/config.py +51 -0
  184. modelopt/torch/sparsity/magnitude.py +148 -0
  185. modelopt/torch/sparsity/mode.py +204 -0
  186. modelopt/torch/sparsity/module.py +89 -0
  187. modelopt/torch/sparsity/plugins/__init__.py +27 -0
  188. modelopt/torch/sparsity/plugins/megatron.py +89 -0
  189. modelopt/torch/sparsity/searcher.py +84 -0
  190. modelopt/torch/sparsity/sparsegpt.py +276 -0
  191. modelopt/torch/sparsity/sparsification.py +123 -0
  192. modelopt/torch/speculative/__init__.py +20 -0
  193. modelopt/torch/speculative/config.py +72 -0
  194. modelopt/torch/speculative/eagle/__init__.py +19 -0
  195. modelopt/torch/speculative/eagle/conversion.py +59 -0
  196. modelopt/torch/speculative/eagle/eagle_model.py +32 -0
  197. modelopt/torch/speculative/eagle/utils.py +94 -0
  198. modelopt/torch/speculative/medusa/__init__.py +19 -0
  199. modelopt/torch/speculative/medusa/conversion.py +59 -0
  200. modelopt/torch/speculative/medusa/medusa_model.py +32 -0
  201. modelopt/torch/speculative/mode.py +115 -0
  202. modelopt/torch/speculative/mtp/__init__.py +19 -0
  203. modelopt/torch/speculative/mtp/conversion.py +60 -0
  204. modelopt/torch/speculative/mtp/mtp_model.py +34 -0
  205. modelopt/torch/speculative/mtp/utils.py +36 -0
  206. modelopt/torch/speculative/plugins/__init__.py +30 -0
  207. modelopt/torch/speculative/plugins/megatron.py +1426 -0
  208. modelopt/torch/speculative/plugins/transformers.py +480 -0
  209. modelopt/torch/speculative/speculative_decoding.py +55 -0
  210. modelopt/torch/speculative/utils.py +230 -0
  211. modelopt/torch/trace/__init__.py +25 -0
  212. modelopt/torch/trace/analyzer.py +1380 -0
  213. modelopt/torch/trace/modules/__init__.py +19 -0
  214. modelopt/torch/trace/modules/concat.py +387 -0
  215. modelopt/torch/trace/modules/nn.py +157 -0
  216. modelopt/torch/trace/plugins/__init__.py +34 -0
  217. modelopt/torch/trace/plugins/megatron.py +29 -0
  218. modelopt/torch/trace/plugins/transformers.py +58 -0
  219. modelopt/torch/trace/symbols.py +544 -0
  220. modelopt/torch/trace/tracer.py +330 -0
  221. modelopt/torch/utils/__init__.py +28 -0
  222. modelopt/torch/utils/_pytree.py +133 -0
  223. modelopt/torch/utils/cpp_extension.py +91 -0
  224. modelopt/torch/utils/dataset_utils.py +425 -0
  225. modelopt/torch/utils/distributed.py +323 -0
  226. modelopt/torch/utils/graph.py +125 -0
  227. modelopt/torch/utils/image_processor.py +115 -0
  228. modelopt/torch/utils/import_utils.py +35 -0
  229. modelopt/torch/utils/list.py +59 -0
  230. modelopt/torch/utils/logging.py +127 -0
  231. modelopt/torch/utils/memory_monitor.py +146 -0
  232. modelopt/torch/utils/network.py +609 -0
  233. modelopt/torch/utils/perf.py +90 -0
  234. modelopt/torch/utils/random.py +160 -0
  235. modelopt/torch/utils/speech_dataset_utils.py +128 -0
  236. modelopt/torch/utils/tensor.py +55 -0
  237. modelopt/torch/utils/vlm_dataset_utils.py +111 -0
  238. nvidia_modelopt-0.27.0.dist-info/METADATA +196 -0
  239. nvidia_modelopt-0.27.0.dist-info/RECORD +242 -0
  240. nvidia_modelopt-0.27.0.dist-info/WHEEL +5 -0
  241. nvidia_modelopt-0.27.0.dist-info/licenses/LICENSE +14 -0
  242. nvidia_modelopt-0.27.0.dist-info/top_level.txt +1 -0
modelopt/__init__.py ADDED
@@ -0,0 +1,42 @@
1
+ # SPDX-FileCopyrightText: Copyright (c) 2024 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
2
+ # SPDX-License-Identifier: Apache-2.0
3
+ #
4
+ # Licensed under the Apache License, Version 2.0 (the "License");
5
+ # you may not use this file except in compliance with the License.
6
+ # You may obtain a copy of the License at
7
+ #
8
+ # http://www.apache.org/licenses/LICENSE-2.0
9
+ #
10
+ # Unless required by applicable law or agreed to in writing, software
11
+ # distributed under the License is distributed on an "AS IS" BASIS,
12
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ # See the License for the specific language governing permissions and
14
+ # limitations under the License.
15
+
16
+ """Nvidia TensorRT Model Optimizer (modelopt)."""
17
+
18
+ import sys as _sys
19
+ import warnings as _warnings
20
+ from importlib.metadata import version as _version
21
+
22
+ __version__ = _version("nvidia-modelopt")
23
+
24
+
25
+ try:
26
+ # Import from local source if available
27
+ from . import core
28
+
29
+ __core_version__ = __version__
30
+ except ImportError:
31
+ # Import from nvidia-modelopt-core wheel installation
32
+ import modelopt_core as core # type: ignore[no-redef]
33
+
34
+ _sys.modules["modelopt.core"] = core
35
+ __core_version__ = _version("nvidia-modelopt-core")
36
+
37
+ # Versions need to be the same for compatibility
38
+ if __version__.split(".")[:2] != __core_version__.split(".")[:2]:
39
+ _warnings.warn(
40
+ f"Version mismatch between nvidia-modelopt ({__version__}) and nvidia-modelopt-core"
41
+ f" ({__core_version__}). Please ensure both versions are the same for compatibility."
42
+ )
@@ -0,0 +1,16 @@
1
+ # SPDX-FileCopyrightText: Copyright (c) 2024 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
2
+ # SPDX-License-Identifier: Apache-2.0
3
+ #
4
+ # Licensed under the Apache License, Version 2.0 (the "License");
5
+ # you may not use this file except in compliance with the License.
6
+ # You may obtain a copy of the License at
7
+ #
8
+ # http://www.apache.org/licenses/LICENSE-2.0
9
+ #
10
+ # Unless required by applicable law or agreed to in writing, software
11
+ # distributed under the License is distributed on an "AS IS" BASIS,
12
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ # See the License for the specific language governing permissions and
14
+ # limitations under the License.
15
+
16
+ """Model Optimizer's deployment package."""
@@ -0,0 +1,33 @@
1
+ # SPDX-FileCopyrightText: Copyright (c) 2024 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
2
+ # SPDX-License-Identifier: Apache-2.0
3
+ #
4
+ # Licensed under the Apache License, Version 2.0 (the "License");
5
+ # you may not use this file except in compliance with the License.
6
+ # You may obtain a copy of the License at
7
+ #
8
+ # http://www.apache.org/licenses/LICENSE-2.0
9
+ #
10
+ # Unless required by applicable law or agreed to in writing, software
11
+ # distributed under the License is distributed on an "AS IS" BASIS,
12
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ # See the License for the specific language governing permissions and
14
+ # limitations under the License.
15
+
16
+ """LLM deployment utils with tensorrt_llm."""
17
+
18
+ from mpi4py import MPI
19
+
20
+ # Pre load MPI libs to avoid tensorrt_llm importing failures.
21
+ print(f"Loaded mpi lib {MPI.__file__} successfully")
22
+
23
+ # Pre import tensorrt_llm
24
+ try:
25
+ import tensorrt_llm
26
+ except Exception as e:
27
+ print(
28
+ "tensorrt_llm package is not installed. Please build or install tensorrt_llm package"
29
+ " properly before calling the llm deployment API."
30
+ )
31
+ raise (e)
32
+
33
+ from .generate import * # noqa
@@ -0,0 +1,297 @@
1
+ # SPDX-FileCopyrightText: Copyright (c) 2024 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
2
+ # SPDX-License-Identifier: Apache-2.0
3
+ #
4
+ # Licensed under the Apache License, Version 2.0 (the "License");
5
+ # you may not use this file except in compliance with the License.
6
+ # You may obtain a copy of the License at
7
+ #
8
+ # http://www.apache.org/licenses/LICENSE-2.0
9
+ #
10
+ # Unless required by applicable law or agreed to in writing, software
11
+ # distributed under the License is distributed on an "AS IS" BASIS,
12
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ # See the License for the specific language governing permissions and
14
+ # limitations under the License.
15
+
16
+ """A wrapper over the TensorRT-LLM high level API runner."""
17
+
18
+ import json
19
+ from pathlib import Path
20
+ from typing import Any, Iterable, Optional, Union
21
+
22
+ import tensorrt_llm
23
+ import torch
24
+ from packaging.version import parse
25
+ from tensorrt_llm import SamplingParams
26
+ from tensorrt_llm._torch.pyexecutor.config import PyTorchConfig
27
+ from tensorrt_llm.bindings.executor import DecodingConfig
28
+ from tensorrt_llm.llmapi import KvCacheConfig as TRT_KvCacheConfig
29
+ from tensorrt_llm.llmapi.llm import LLM as TRT_LLM
30
+ from tensorrt_llm.llmapi.tokenizer import TokenizerBase, TransformersTokenizer
31
+
32
+
33
+ def _sanitize_temperature_and_top_p(temperature, top_p):
34
+ assert temperature >= 0.0, "Temperature must be greater than 0.0."
35
+
36
+ # TRT LLM acccepts temperature values only greater than 0.0
37
+ temperature = max(temperature, 0.001)
38
+
39
+ kwargs = {"temperature": temperature}
40
+ if top_p is not None:
41
+ # cpp executor only supports topP.value() > 0.f
42
+ top_p = 1e-4 if top_p == 0 else top_p
43
+ kwargs["top_p"] = top_p
44
+
45
+ return kwargs
46
+
47
+
48
+ class LLM(TRT_LLM):
49
+ """A wrapper over the ``tensorrt_llm.llmapi.llm.LLM`` for LLM profiling and validation."""
50
+
51
+ def _build_trt_llm_from_config(
52
+ self, config, engine_dir, tokenizer, kv_cache_config, medusa_choices
53
+ ):
54
+ build_config = config["build_config"]
55
+ world_size = config.get("pretrained_config", {}).get("mapping", {}).get("world_size", 1)
56
+ max_tokens_kv_cache = build_config["max_seq_len"] * build_config["max_batch_size"]
57
+
58
+ trt_kv_cache_config = TRT_KvCacheConfig(enable_block_reuse=False)
59
+
60
+ # If not specified, free_gpu_memory_fraction is set to the default TRT LLM value 0.9
61
+ trt_kv_cache_config.free_gpu_memory_fraction = kv_cache_config.get(
62
+ "free_gpu_memory_fraction", 0.9
63
+ )
64
+
65
+ # If not specified, max_tokens is set to the max value calculated above.
66
+ trt_kv_cache_config.max_tokens = kv_cache_config.get("max_tokens", max_tokens_kv_cache)
67
+
68
+ kwargs = {}
69
+ if medusa_choices is not None:
70
+ decoding_config = DecodingConfig()
71
+ decoding_config.medusa_choices = medusa_choices
72
+ kwargs["decoding_config"] = decoding_config
73
+ assert world_size == 1, "decoding_config does not support multi TP in HLAPI."
74
+
75
+ if tokenizer is None:
76
+ # Assume the tokenizer is stored in the engine_dir if not specified.
77
+ tokenizer = engine_dir
78
+
79
+ # CustomSentencePieceTokenizer will not be recognized by llmapi, wrapping it around TransformersTokenizer
80
+ if type(tokenizer).__name__ in ["CustomSentencePieceTokenizer"]:
81
+ tokenizer = TransformersTokenizer(tokenizer)
82
+
83
+ super().__init__(
84
+ model=engine_dir,
85
+ tokenizer=tokenizer,
86
+ kv_cache_config=trt_kv_cache_config,
87
+ **kwargs,
88
+ )
89
+
90
+ def _build_torch_llm_from_config(self, checkpoint_dir, tokenizer, tp, trust_remote_code):
91
+ pytorch_config = PyTorchConfig(use_cuda_graph=True)
92
+
93
+ kwargs = {}
94
+ if tokenizer is not None:
95
+ kwargs["tokenizer"] = tokenizer
96
+
97
+ if tp < 1:
98
+ tp = torch.cuda.device_count()
99
+
100
+ # Sometimes 90% of the GPU memory is not enough for the TRT LLM torch engine.
101
+ trt_kv_cache_config = TRT_KvCacheConfig(
102
+ enable_block_reuse=False, free_gpu_memory_fraction=0.85
103
+ )
104
+
105
+ super().__init__(
106
+ backend="pytorch",
107
+ model=checkpoint_dir,
108
+ tensor_parallel_size=tp,
109
+ trust_remote_code=trust_remote_code,
110
+ enable_chunked_prefill=True,
111
+ pytorch_backend_config=pytorch_config,
112
+ kv_cache_config=trt_kv_cache_config,
113
+ **kwargs,
114
+ )
115
+
116
+ def __init__(
117
+ self,
118
+ checkpoint_dir: Union[str, Path],
119
+ tokenizer: Optional[Union[str, Path, TokenizerBase]] = None,
120
+ kv_cache_config: dict[str, Union[int, float]] = {},
121
+ medusa_choices: Any = None,
122
+ tp: int = 0,
123
+ trust_remote_code: bool = False,
124
+ ):
125
+ """Initializes the LLM runner class.
126
+
127
+ Args:
128
+ engine_dir: the directory path of the TensorRT-LLM engine.
129
+ tokenizer: the tokenizer. For example, a tokenizer from the Huggingface model.
130
+ kv_cache_config: the kv cache config as a dict. Please refer to
131
+ https://nvidia.github.io/TensorRT-LLM/performance/performance-tuning-guide/
132
+ medusa_choices: The medusa choices for the decoding config.
133
+ tp: the tensor parallel size (for the torch backend). If 0, it will be set to the number of GPUs.
134
+ trust_remote_code: whether to trust the remote code (for the torch backend).
135
+ """
136
+ assert parse(tensorrt_llm.__version__) >= parse("0.17.0")
137
+
138
+ with open(Path(checkpoint_dir) / "config.json", "r") as config_file:
139
+ config = json.load(config_file)
140
+
141
+ if "build_config" in config:
142
+ self._build_trt_llm_from_config(
143
+ config, checkpoint_dir, tokenizer, kv_cache_config, medusa_choices
144
+ )
145
+
146
+ self._is_torch = False
147
+ self._max_seq_len = self.args.build_config.max_seq_len
148
+ self._max_beam_width = self.args.build_config.max_beam_width
149
+ self._gather_context_logits = self.args.build_config.gather_context_logits
150
+ else:
151
+ assert medusa_choices is None, (
152
+ "medusa_choices is not supported with the torch llmapi"
153
+ )
154
+
155
+ self._build_torch_llm_from_config(checkpoint_dir, tokenizer, tp, trust_remote_code)
156
+ self._is_torch = True
157
+ self._max_seq_len = config["max_position_embeddings"]
158
+ self._max_beam_width = 1
159
+ self._gather_context_logits = False
160
+
161
+ @property
162
+ def max_seq_len(self):
163
+ """Get the max sequence length from the LLM instance."""
164
+ return self._max_seq_len
165
+
166
+ @property
167
+ def max_beam_width(self):
168
+ """Get the max beam width from the LLM instance."""
169
+ return self._max_beam_width
170
+
171
+ @property
172
+ def gather_context_logits(self):
173
+ """Returns whether the context_logits can be returned from the LLM instance."""
174
+ return self._gather_context_logits
175
+
176
+ def _generate(
177
+ self,
178
+ prompts: Union[Iterable[str], Iterable[list[int]]],
179
+ max_new_tokens: int,
180
+ temperature: float = 1.0,
181
+ top_p: float = None,
182
+ stop_words: list[str] = None,
183
+ ):
184
+ assert temperature >= 0.0, "Temperature must be greater than 0.0."
185
+
186
+ # TODO: Remove this once torch backend supports stop words
187
+ if self._is_torch:
188
+ stop_words = None
189
+
190
+ beam_width = self.max_beam_width
191
+ kwargs = _sanitize_temperature_and_top_p(temperature, top_p)
192
+ sampling_config = SamplingParams(
193
+ max_tokens=max_new_tokens, beam_width=beam_width, stop=stop_words, **kwargs
194
+ )
195
+
196
+ return self.generate(prompts, sampling_params=sampling_config, use_tqdm=False)
197
+
198
+ def generate_tokens(
199
+ self,
200
+ prompts: Union[Iterable[str], Iterable[list[int]]],
201
+ max_new_tokens: int,
202
+ temperature: float = 1.0,
203
+ top_p: float = None,
204
+ stop_words: list[str] = None,
205
+ ) -> Union[list[list[int]], list[list[list[int]]]]:
206
+ """Generates the tokens based on the input prompts.
207
+
208
+ Args:
209
+ prompts: The input prompts. Could be a list of strings or token lists.
210
+ max_new_tokens: The max output token length.
211
+ temperature: The sampling temperature.
212
+ top_p: The nucleus sampling parameter.
213
+ stop_words: A list of words that the generate stops on.
214
+
215
+ Returns:
216
+ a list of output token lists if max_beam_width is 1 or a 3D list with shape [batch, beam, sequence_len].
217
+ """
218
+ outputs = self._generate(prompts, max_new_tokens, temperature, top_p, stop_words)
219
+ output_tokens = []
220
+
221
+ beam_width = self.max_beam_width
222
+ for request_output in outputs:
223
+ token_ids = [
224
+ completion_output.token_ids for completion_output in request_output.outputs
225
+ ]
226
+ if beam_width == 1:
227
+ # each output_text is a single list of tokens.
228
+ output_tokens += token_ids
229
+ else:
230
+ # each output_text is a list of beam searched token lists.
231
+ output_tokens.append(token_ids)
232
+
233
+ return output_tokens
234
+
235
+ def generate_text(
236
+ self,
237
+ prompts: Union[Iterable[str], Iterable[list[int]]],
238
+ max_new_tokens: int,
239
+ temperature: float = 1.0,
240
+ top_p: float = None,
241
+ stop_words: list[str] = None,
242
+ ) -> Union[list[str], list[list[str]]]:
243
+ """Generates the text based on the input prompts.
244
+
245
+ Args:
246
+ prompts: The input prompts. Could be a list of strings or token lists.
247
+ max_new_tokens: The max output token length.
248
+ temperature: The sampling temperature
249
+ stop_words: A list of words the generate will stop on.
250
+
251
+ Returns:
252
+ a list of output text strings if max_beam_width is 1 or a 2D list with shape [batch, beam].
253
+ """
254
+ outputs = self._generate(prompts, max_new_tokens, temperature, top_p, stop_words)
255
+ output_texts = []
256
+
257
+ beam_width = self.max_beam_width
258
+ for request_output in outputs:
259
+ texts = [completion_output.text for completion_output in request_output.outputs]
260
+ if beam_width == 1:
261
+ # each output_text is a single text string.
262
+ output_texts += texts
263
+ else:
264
+ # each output_text is a list of beam searched texts
265
+ output_texts.append(texts)
266
+
267
+ return output_texts
268
+
269
+ def generate_context_logits(
270
+ self,
271
+ prompts: Union[Iterable[str], Iterable[list[int]]],
272
+ temperature: float = 1.0,
273
+ top_p: float = None,
274
+ ) -> list[torch.tensor]:
275
+ """Generates the context logits based on the input prompts.
276
+
277
+ Args:
278
+ prompts: The input prompts. Could be a list of strings or token lists.
279
+ temperature: The sampling temperature.
280
+ top_p: The nucleus sampling parameter.
281
+
282
+ Returns:
283
+ a tensor list of the context_logits.
284
+ """
285
+ assert self.gather_context_logits, (
286
+ "Please enable gather_context_logits flag when building the engine."
287
+ )
288
+ assert temperature >= 0.0, "Temperature must be greater than 0.0."
289
+
290
+ kwargs = _sanitize_temperature_and_top_p(temperature, top_p)
291
+ kwargs["return_context_logits"] = True
292
+
293
+ sampling_config = SamplingParams(max_tokens=1, beam_width=1, **kwargs)
294
+
295
+ outputs = self.generate(prompts, sampling_params=sampling_config, use_tqdm=False)
296
+
297
+ return [output.context_logits for output in outputs]
@@ -0,0 +1,184 @@
1
+ # SPDX-FileCopyrightText: Copyright (c) 2024 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
2
+ # SPDX-License-Identifier: Apache-2.0
3
+ #
4
+ # Licensed under the Apache License, Version 2.0 (the "License");
5
+ # you may not use this file except in compliance with the License.
6
+ # You may obtain a copy of the License at
7
+ #
8
+ # http://www.apache.org/licenses/LICENSE-2.0
9
+ #
10
+ # Unless required by applicable law or agreed to in writing, software
11
+ # distributed under the License is distributed on an "AS IS" BASIS,
12
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ # See the License for the specific language governing permissions and
14
+ # limitations under the License.
15
+
16
+ """The utils to support Nemo models."""
17
+
18
+ import warnings
19
+ from pathlib import Path
20
+
21
+ import numpy as np
22
+ import torch
23
+ from transformers import GPT2Tokenizer, PreTrainedTokenizer, T5Tokenizer
24
+
25
+ try:
26
+ from nemo.collections.common.tokenizers.sentencepiece_tokenizer import SentencePieceTokenizer
27
+
28
+ sentence_piece_tokenizer_available = True
29
+ except Exception:
30
+ sentence_piece_tokenizer_available = False
31
+ SentencePieceTokenizer = PreTrainedTokenizer
32
+
33
+
34
+ class CustomSentencePieceTokenizer(SentencePieceTokenizer):
35
+ """Custom tokenizer based on Nemo SentencePieceTokenizer.
36
+
37
+ This extension of SentencePieceTokenizer is to make API consistent with HuggingFace tokenizers
38
+ in order to run evaluation tools in examples/tensorrt_llm/scripts/nemo_example.sh script.
39
+ """
40
+
41
+ def __init__(self, *args, **kwargs):
42
+ """Constructor method with extra check for non-legacy SentencePieceTokenizer variant."""
43
+ super().__init__(*args, **kwargs)
44
+ assert not self.legacy, "Only non-legacy tokenizer is supported"
45
+
46
+ @property
47
+ def pad_token(self):
48
+ """pad_token."""
49
+ return self.pad_id
50
+
51
+ @property
52
+ def eos_token(self):
53
+ """eos_token."""
54
+ return self.eos_id
55
+
56
+ @property
57
+ def pad_token_id(self):
58
+ """pad_token_id."""
59
+ return self.pad_id
60
+
61
+ @property
62
+ def eos_token_id(self):
63
+ """eos_token_id."""
64
+ return self.eos_id
65
+
66
+ def encode(self, text, return_tensors=None, max_length=None, **kwargs):
67
+ """Method introduced for HF tokenizers API consistency for evaluation scripts.
68
+
69
+ Note: kwargs other than return_tensors and max_length are ignored.
70
+ """
71
+ output = self.tokenizer.encode_as_ids(text)
72
+ if max_length is not None:
73
+ if isinstance(text, str):
74
+ output = output[:max_length]
75
+ if isinstance(text, list):
76
+ output = [x[:max_length] for x in output]
77
+ if return_tensors == "pt":
78
+ # Only plain text input is supported since for list of strings some padding needs to be introduced
79
+ assert isinstance(text, str), (
80
+ "Returning 'pt' tensors is only supported for simple text input"
81
+ )
82
+ output = torch.LongTensor(output).reshape((1, -1))
83
+ return output
84
+
85
+ def batch_encode_plus(self, texts, **kwargs):
86
+ """Method introduced for HF tokenizers API consistency for evaluation scripts.
87
+
88
+ Note: kwargs are ignored.
89
+ """
90
+ assert isinstance(texts, list), f"Expected list of texts got {texts}"
91
+ return {"input_ids": self.tokenizer.encode_as_ids(texts)}
92
+
93
+ def decode(self, ids, **kwargs):
94
+ """MMethod introduced for HF tokenizers API consistency for evaluation scripts.
95
+
96
+ Note: kwargs are ignored.
97
+ """
98
+ if isinstance(ids, np.ndarray) or torch.is_tensor(ids):
99
+ ids = ids.tolist()
100
+ return self.tokenizer.decode(ids)
101
+
102
+ def batch_decode(self, ids, **kwargs):
103
+ """Method introduced for HF tokenizers API consistency for evaluation scripts."""
104
+ return self.decode(ids, **kwargs)
105
+
106
+
107
+ def _build_tokenizer(tokenizer_config: dict):
108
+ if tokenizer_config["library"] == "sentencepiece":
109
+ # Model Optimizer modification.
110
+ # Turn off legacy model by default: See https://github.com/huggingface/transformers/pull/24622
111
+ tokenizer = T5Tokenizer(tokenizer_config["model"], extra_ids=0, legacy=False)
112
+ elif "GPT2" in tokenizer_config["type"]:
113
+ tokenizer = GPT2Tokenizer(tokenizer_config["vocab_file"], tokenizer_config["merge_file"])
114
+ else:
115
+ raise ValueError(f"Tokenizer type {tokenizer_config['library']} not handled")
116
+
117
+ if tokenizer.bos_token_id is None:
118
+ tokenizer.add_special_tokens({"bos_token": "<s>"})
119
+ if tokenizer.eos_token_id is None:
120
+ tokenizer.add_special_tokens({"eos_token": "</s>"})
121
+
122
+ return tokenizer
123
+
124
+
125
+ def get_tokenzier(tokenizer_dir_or_path: Path) -> PreTrainedTokenizer:
126
+ """Loads the tokenizer from the decoded NEMO weights dir."""
127
+ # TODO: Remove this function sometime in the future
128
+ warnings.warn(
129
+ (
130
+ "Function get_tokenzier is deprecated and may be removed soon. "
131
+ "Please consider using get_nemo_tokenizer instead."
132
+ ),
133
+ DeprecationWarning,
134
+ )
135
+ model_path = (
136
+ tokenizer_dir_or_path / "tokenizer.model"
137
+ if tokenizer_dir_or_path.is_dir()
138
+ else tokenizer_dir_or_path
139
+ )
140
+ tokenizer_config = {"library": "sentencepiece", "model": str(model_path)}
141
+ return _build_tokenizer(tokenizer_config)
142
+
143
+
144
+ def get_nemo_tokenizer(tokenizer_cfg_path: str):
145
+ """Build tokenizer from Nemo tokenizer config.
146
+
147
+ Refer to the logic of get_nmt_tokenizer function on how to instantiate tokenizers in Nemo, see
148
+ https://github.com/NVIDIA/NeMo/blob/main/nemo/collections/nlp/modules/common/tokenizer_utils.py.
149
+ """
150
+ from nemo.collections.common.tokenizers.huggingface.auto_tokenizer import AutoTokenizer
151
+ from omegaconf import OmegaConf
152
+
153
+ print(f"Initializing tokenizer from tokenizer config {tokenizer_cfg_path}")
154
+ tokenizer_cfg = OmegaConf.load(tokenizer_cfg_path)
155
+
156
+ library = tokenizer_cfg.library
157
+ legacy = tokenizer_cfg.get("sentencepiece_legacy", library == "sentencepiece")
158
+ special_tokens_dict = tokenizer_cfg.get("special_tokens", {})
159
+
160
+ if library == "huggingface":
161
+ print(f"Getting HuggingFace AutoTokenizer with pretrained_model_name: {tokenizer_cfg.type}")
162
+ tokenizer = AutoTokenizer(
163
+ pretrained_model_name=tokenizer_cfg.type,
164
+ vocab_file=tokenizer_cfg.get("vocab_file", None),
165
+ merges_file=tokenizer_cfg.get("merge_file", None),
166
+ use_fast=tokenizer_cfg.get("use_fast", False),
167
+ **special_tokens_dict,
168
+ )
169
+ print("Unwrapping HuggingFace tokenizer from Nemo AutoTokenizer")
170
+ # TODO: Either Nemo tokenizer API alignment is needed https://github.com/NVIDIA/NeMo/pull/8818
171
+ # or alternatively we can use only HuggingFace tokenizers in future. Current workaround
172
+ # proposed here is to unwrap the HuggingFace tokenizer from Nemo AutoTokenizer class:
173
+ tokenizer = tokenizer.tokenizer
174
+ elif library == "sentencepiece":
175
+ print(f"Getting SentencePiece with model: {tokenizer_cfg.model}")
176
+ if not sentence_piece_tokenizer_available:
177
+ warnings.warn("Cannot import nemo package, falling back to HF PreTrainedTokenizer!")
178
+ tokenizer = CustomSentencePieceTokenizer(model_path=tokenizer_cfg.model, legacy=legacy)
179
+ else:
180
+ raise NotImplementedError(
181
+ "Currently we only support 'huggingface' and 'sentencepiece' tokenizer libraries."
182
+ )
183
+
184
+ return tokenizer
@@ -0,0 +1,35 @@
1
+ # SPDX-FileCopyrightText: Copyright (c) 2024 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
2
+ # SPDX-License-Identifier: Apache-2.0
3
+ #
4
+ # Licensed under the Apache License, Version 2.0 (the "License");
5
+ # you may not use this file except in compliance with the License.
6
+ # You may obtain a copy of the License at
7
+ #
8
+ # http://www.apache.org/licenses/LICENSE-2.0
9
+ #
10
+ # Unless required by applicable law or agreed to in writing, software
11
+ # distributed under the License is distributed on an "AS IS" BASIS,
12
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ # See the License for the specific language governing permissions and
14
+ # limitations under the License.
15
+
16
+ """Model optimization subpackage for onnx."""
17
+
18
+ import sys
19
+ import warnings
20
+
21
+ MIN_PYTHON_VERSION = (3, 10)
22
+
23
+ try:
24
+ from . import quantization # noqa: F401
25
+ except ImportError as e:
26
+ raise ImportError(f"{e}\nPlease install optional ``[onnx]`` dependencies.")
27
+
28
+
29
+ # Check the current Python version
30
+ if sys.version_info < MIN_PYTHON_VERSION:
31
+ warnings.warn(
32
+ f"This package requires Python {MIN_PYTHON_VERSION[0]}.{MIN_PYTHON_VERSION[1]} or higher. "
33
+ f"You are using Python {sys.version_info[0]}.{sys.version_info[1]}.",
34
+ UserWarning,
35
+ )