nvidia-modelopt 0.35.0__py3-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 (272) hide show
  1. modelopt/__init__.py +20 -0
  2. modelopt/deploy/__init__.py +16 -0
  3. modelopt/deploy/llm/__init__.py +30 -0
  4. modelopt/deploy/llm/generate.py +345 -0
  5. modelopt/onnx/__init__.py +34 -0
  6. modelopt/onnx/autocast/__init__.py +19 -0
  7. modelopt/onnx/autocast/__main__.py +187 -0
  8. modelopt/onnx/autocast/convert.py +202 -0
  9. modelopt/onnx/autocast/graphsanitizer.py +422 -0
  10. modelopt/onnx/autocast/logging_config.py +78 -0
  11. modelopt/onnx/autocast/nodeclassifier.py +416 -0
  12. modelopt/onnx/autocast/precisionconverter.py +1032 -0
  13. modelopt/onnx/autocast/referencerunner.py +159 -0
  14. modelopt/onnx/autocast/utils.py +117 -0
  15. modelopt/onnx/llm_export_utils/__init__.py +16 -0
  16. modelopt/onnx/llm_export_utils/export_utils.py +162 -0
  17. modelopt/onnx/llm_export_utils/quantization_utils.py +122 -0
  18. modelopt/onnx/llm_export_utils/surgeon_utils.py +120 -0
  19. modelopt/onnx/logging_config.py +77 -0
  20. modelopt/onnx/op_types.py +300 -0
  21. modelopt/onnx/quantization/__init__.py +20 -0
  22. modelopt/onnx/quantization/__main__.py +291 -0
  23. modelopt/onnx/quantization/calib_utils.py +178 -0
  24. modelopt/onnx/quantization/extensions.py +35 -0
  25. modelopt/onnx/quantization/fp8.py +375 -0
  26. modelopt/onnx/quantization/graph_utils.py +1479 -0
  27. modelopt/onnx/quantization/gs_patching.py +112 -0
  28. modelopt/onnx/quantization/int4.py +1347 -0
  29. modelopt/onnx/quantization/int8.py +283 -0
  30. modelopt/onnx/quantization/operators.py +121 -0
  31. modelopt/onnx/quantization/ort_patching.py +1766 -0
  32. modelopt/onnx/quantization/ort_utils.py +346 -0
  33. modelopt/onnx/quantization/partitioning.py +439 -0
  34. modelopt/onnx/quantization/qdq_utils.py +1349 -0
  35. modelopt/onnx/quantization/quant_utils.py +283 -0
  36. modelopt/onnx/quantization/quantize.py +528 -0
  37. modelopt/onnx/quantization/src/modelopt_round_and_pack_ext.cpp +127 -0
  38. modelopt/onnx/trt_utils.py +424 -0
  39. modelopt/onnx/utils.py +753 -0
  40. modelopt/torch/__init__.py +41 -0
  41. modelopt/torch/_deploy/__init__.py +23 -0
  42. modelopt/torch/_deploy/_runtime/__init__.py +29 -0
  43. modelopt/torch/_deploy/_runtime/common.py +72 -0
  44. modelopt/torch/_deploy/_runtime/ort_client.py +193 -0
  45. modelopt/torch/_deploy/_runtime/registry.py +83 -0
  46. modelopt/torch/_deploy/_runtime/runtime_client.py +154 -0
  47. modelopt/torch/_deploy/_runtime/tensorrt/constants.py +108 -0
  48. modelopt/torch/_deploy/_runtime/tensorrt/engine_builder.py +324 -0
  49. modelopt/torch/_deploy/_runtime/tensorrt/hw_param_config.py +51 -0
  50. modelopt/torch/_deploy/_runtime/tensorrt/layerwise_profiling.py +178 -0
  51. modelopt/torch/_deploy/_runtime/tensorrt/parse_trtexec_log.py +151 -0
  52. modelopt/torch/_deploy/_runtime/tensorrt/tensorrt_utils.py +200 -0
  53. modelopt/torch/_deploy/_runtime/trt_client.py +219 -0
  54. modelopt/torch/_deploy/compilation.py +142 -0
  55. modelopt/torch/_deploy/device_model.py +157 -0
  56. modelopt/torch/_deploy/profiling.py +193 -0
  57. modelopt/torch/_deploy/utils/__init__.py +18 -0
  58. modelopt/torch/_deploy/utils/onnx_optimizer.py +120 -0
  59. modelopt/torch/_deploy/utils/onnx_utils.py +58 -0
  60. modelopt/torch/_deploy/utils/torch_onnx.py +593 -0
  61. modelopt/torch/distill/__init__.py +28 -0
  62. modelopt/torch/distill/config.py +130 -0
  63. modelopt/torch/distill/distillation.py +84 -0
  64. modelopt/torch/distill/distillation_model.py +318 -0
  65. modelopt/torch/distill/loss_balancers.py +140 -0
  66. modelopt/torch/distill/losses.py +275 -0
  67. modelopt/torch/distill/mode.py +223 -0
  68. modelopt/torch/distill/plugins/__init__.py +24 -0
  69. modelopt/torch/distill/plugins/huggingface.py +110 -0
  70. modelopt/torch/distill/plugins/megatron.py +476 -0
  71. modelopt/torch/distill/registry.py +23 -0
  72. modelopt/torch/export/__init__.py +24 -0
  73. modelopt/torch/export/convert_hf_config.py +117 -0
  74. modelopt/torch/export/distribute.py +300 -0
  75. modelopt/torch/export/hf_config_map.py +84 -0
  76. modelopt/torch/export/layer_utils.py +1893 -0
  77. modelopt/torch/export/mcore_config_map.py +25 -0
  78. modelopt/torch/export/model_config.py +623 -0
  79. modelopt/torch/export/model_config_export.py +552 -0
  80. modelopt/torch/export/model_config_utils.py +392 -0
  81. modelopt/torch/export/model_utils.py +71 -0
  82. modelopt/torch/export/plugins/__init__.py +21 -0
  83. modelopt/torch/export/plugins/mcore_common.py +67 -0
  84. modelopt/torch/export/plugins/mcore_custom.py +530 -0
  85. modelopt/torch/export/plugins/mcore_deepseek.py +143 -0
  86. modelopt/torch/export/plugins/mcore_gptoss.py +71 -0
  87. modelopt/torch/export/plugins/mcore_llama.py +164 -0
  88. modelopt/torch/export/plugins/mcore_nemotron.py +90 -0
  89. modelopt/torch/export/plugins/mcore_qwen.py +99 -0
  90. modelopt/torch/export/plugins/megatron_importer.py +647 -0
  91. modelopt/torch/export/postprocess.py +847 -0
  92. modelopt/torch/export/quant_utils.py +1069 -0
  93. modelopt/torch/export/tensorrt_llm_type.py +42 -0
  94. modelopt/torch/export/tensorrt_llm_utils.py +405 -0
  95. modelopt/torch/export/transformer_engine.py +94 -0
  96. modelopt/torch/export/unified_export_hf.py +537 -0
  97. modelopt/torch/export/unified_export_megatron.py +1164 -0
  98. modelopt/torch/nas/__init__.py +27 -0
  99. modelopt/torch/nas/algorithms.py +856 -0
  100. modelopt/torch/nas/autonas.py +808 -0
  101. modelopt/torch/nas/conversion.py +119 -0
  102. modelopt/torch/nas/hparams/__init__.py +19 -0
  103. modelopt/torch/nas/hparams/concat.py +319 -0
  104. modelopt/torch/nas/hparams/container.py +48 -0
  105. modelopt/torch/nas/modules/__init__.py +21 -0
  106. modelopt/torch/nas/modules/container.py +99 -0
  107. modelopt/torch/nas/modules/conv.py +254 -0
  108. modelopt/torch/nas/modules/linear.py +76 -0
  109. modelopt/torch/nas/modules/norm.py +193 -0
  110. modelopt/torch/nas/modules/utils.py +61 -0
  111. modelopt/torch/nas/patch.py +261 -0
  112. modelopt/torch/nas/plugins/__init__.py +29 -0
  113. modelopt/torch/nas/plugins/megatron.py +1497 -0
  114. modelopt/torch/nas/plugins/torch.py +71 -0
  115. modelopt/torch/nas/plugins/transformer_engine.py +42 -0
  116. modelopt/torch/nas/plugins/transformers.py +210 -0
  117. modelopt/torch/nas/registry.py +23 -0
  118. modelopt/torch/nas/search_space.py +260 -0
  119. modelopt/torch/nas/traced_hp.py +149 -0
  120. modelopt/torch/nas/utils.py +408 -0
  121. modelopt/torch/opt/__init__.py +41 -0
  122. modelopt/torch/opt/_hooks.py +98 -0
  123. modelopt/torch/opt/config.py +383 -0
  124. modelopt/torch/opt/conversion.py +620 -0
  125. modelopt/torch/opt/dynamic.py +1367 -0
  126. modelopt/torch/opt/hparam.py +275 -0
  127. modelopt/torch/opt/mode.py +353 -0
  128. modelopt/torch/opt/plugins/__init__.py +38 -0
  129. modelopt/torch/opt/plugins/diffusers.py +40 -0
  130. modelopt/torch/opt/plugins/huggingface.py +162 -0
  131. modelopt/torch/opt/plugins/mcore_dist_checkpointing.py +211 -0
  132. modelopt/torch/opt/plugins/megatron.py +142 -0
  133. modelopt/torch/opt/plugins/peft.py +108 -0
  134. modelopt/torch/opt/plugins/transformers.py +160 -0
  135. modelopt/torch/opt/searcher.py +363 -0
  136. modelopt/torch/opt/utils.py +125 -0
  137. modelopt/torch/prune/__init__.py +26 -0
  138. modelopt/torch/prune/fastnas.py +376 -0
  139. modelopt/torch/prune/gradnas.py +349 -0
  140. modelopt/torch/prune/plugins/__init__.py +24 -0
  141. modelopt/torch/prune/plugins/mcore_minitron.py +263 -0
  142. modelopt/torch/prune/plugins/transformers.py +41 -0
  143. modelopt/torch/prune/pruning.py +211 -0
  144. modelopt/torch/quantization/__init__.py +26 -0
  145. modelopt/torch/quantization/algorithms.py +671 -0
  146. modelopt/torch/quantization/backends/__init__.py +20 -0
  147. modelopt/torch/quantization/backends/fp8_per_tensor_gemm.py +204 -0
  148. modelopt/torch/quantization/backends/gemm_registry.py +156 -0
  149. modelopt/torch/quantization/backends/nvfp4_gemm.py +201 -0
  150. modelopt/torch/quantization/backends/utils.py +28 -0
  151. modelopt/torch/quantization/calib/__init__.py +25 -0
  152. modelopt/torch/quantization/calib/bias.py +172 -0
  153. modelopt/torch/quantization/calib/calibrator.py +63 -0
  154. modelopt/torch/quantization/calib/histogram.py +434 -0
  155. modelopt/torch/quantization/calib/max.py +110 -0
  156. modelopt/torch/quantization/compress.py +227 -0
  157. modelopt/torch/quantization/config.py +1180 -0
  158. modelopt/torch/quantization/conversion.py +389 -0
  159. modelopt/torch/quantization/export_onnx.py +639 -0
  160. modelopt/torch/quantization/extensions.py +89 -0
  161. modelopt/torch/quantization/mode.py +428 -0
  162. modelopt/torch/quantization/model_calib.py +949 -0
  163. modelopt/torch/quantization/model_quant.py +477 -0
  164. modelopt/torch/quantization/nn/__init__.py +26 -0
  165. modelopt/torch/quantization/nn/functional.py +109 -0
  166. modelopt/torch/quantization/nn/modules/__init__.py +16 -0
  167. modelopt/torch/quantization/nn/modules/quant_activations.py +22 -0
  168. modelopt/torch/quantization/nn/modules/quant_batchnorm.py +24 -0
  169. modelopt/torch/quantization/nn/modules/quant_conv.py +123 -0
  170. modelopt/torch/quantization/nn/modules/quant_instancenorm.py +39 -0
  171. modelopt/torch/quantization/nn/modules/quant_linear.py +258 -0
  172. modelopt/torch/quantization/nn/modules/quant_module.py +211 -0
  173. modelopt/torch/quantization/nn/modules/quant_pooling.py +99 -0
  174. modelopt/torch/quantization/nn/modules/quant_rnn.py +527 -0
  175. modelopt/torch/quantization/nn/modules/tensor_quantizer.py +1293 -0
  176. modelopt/torch/quantization/plugins/__init__.py +73 -0
  177. modelopt/torch/quantization/plugins/accelerate.py +214 -0
  178. modelopt/torch/quantization/plugins/apex.py +52 -0
  179. modelopt/torch/quantization/plugins/attention.py +312 -0
  180. modelopt/torch/quantization/plugins/custom.py +192 -0
  181. modelopt/torch/quantization/plugins/diffusers.py +237 -0
  182. modelopt/torch/quantization/plugins/fairscale.py +45 -0
  183. modelopt/torch/quantization/plugins/huggingface.py +736 -0
  184. modelopt/torch/quantization/plugins/megatron.py +462 -0
  185. modelopt/torch/quantization/plugins/peft.py +148 -0
  186. modelopt/torch/quantization/plugins/transformer_engine.py +60 -0
  187. modelopt/torch/quantization/plugins/transformers.py +52 -0
  188. modelopt/torch/quantization/plugins/transformers_trainer.py +426 -0
  189. modelopt/torch/quantization/plugins/trl.py +27 -0
  190. modelopt/torch/quantization/plugins/vllm.py +199 -0
  191. modelopt/torch/quantization/qtensor/__init__.py +24 -0
  192. modelopt/torch/quantization/qtensor/base_qtensor.py +370 -0
  193. modelopt/torch/quantization/qtensor/fp8_tensor.py +151 -0
  194. modelopt/torch/quantization/qtensor/int4_tensor.py +130 -0
  195. modelopt/torch/quantization/qtensor/int8_tensor.py +124 -0
  196. modelopt/torch/quantization/qtensor/mxfp4_tensor.py +144 -0
  197. modelopt/torch/quantization/qtensor/nf4_tensor.py +199 -0
  198. modelopt/torch/quantization/qtensor/nvfp4_tensor.py +295 -0
  199. modelopt/torch/quantization/src/tensor_quant.cpp +77 -0
  200. modelopt/torch/quantization/src/tensor_quant.h +69 -0
  201. modelopt/torch/quantization/src/tensor_quant_fp8.cpp +48 -0
  202. modelopt/torch/quantization/src/tensor_quant_gpu.cu +361 -0
  203. modelopt/torch/quantization/src/tensor_quant_gpu_fp8.cu +122 -0
  204. modelopt/torch/quantization/src/tensor_quant_mx.cu +411 -0
  205. modelopt/torch/quantization/src/tensor_quant_mx.h +247 -0
  206. modelopt/torch/quantization/tensor_quant.py +816 -0
  207. modelopt/torch/quantization/triton/__init__.py +36 -0
  208. modelopt/torch/quantization/triton/fp4_kernel.py +303 -0
  209. modelopt/torch/quantization/utils.py +443 -0
  210. modelopt/torch/sparsity/__init__.py +19 -0
  211. modelopt/torch/sparsity/config.py +51 -0
  212. modelopt/torch/sparsity/magnitude.py +148 -0
  213. modelopt/torch/sparsity/mode.py +203 -0
  214. modelopt/torch/sparsity/module.py +87 -0
  215. modelopt/torch/sparsity/plugins/__init__.py +27 -0
  216. modelopt/torch/sparsity/plugins/megatron.py +93 -0
  217. modelopt/torch/sparsity/searcher.py +84 -0
  218. modelopt/torch/sparsity/sparsegpt.py +276 -0
  219. modelopt/torch/sparsity/sparsification.py +123 -0
  220. modelopt/torch/speculative/__init__.py +20 -0
  221. modelopt/torch/speculative/config.py +100 -0
  222. modelopt/torch/speculative/eagle/__init__.py +20 -0
  223. modelopt/torch/speculative/eagle/conversion.py +67 -0
  224. modelopt/torch/speculative/eagle/default_config.py +50 -0
  225. modelopt/torch/speculative/eagle/eagle_model.py +51 -0
  226. modelopt/torch/speculative/eagle/utils.py +91 -0
  227. modelopt/torch/speculative/medusa/__init__.py +19 -0
  228. modelopt/torch/speculative/medusa/conversion.py +59 -0
  229. modelopt/torch/speculative/medusa/medusa_model.py +32 -0
  230. modelopt/torch/speculative/mode.py +86 -0
  231. modelopt/torch/speculative/plugins/__init__.py +33 -0
  232. modelopt/torch/speculative/plugins/megatron_eagle.py +2119 -0
  233. modelopt/torch/speculative/plugins/megatron_medusa.py +312 -0
  234. modelopt/torch/speculative/plugins/transformers.py +1138 -0
  235. modelopt/torch/speculative/speculative_decoding.py +59 -0
  236. modelopt/torch/speculative/utils.py +364 -0
  237. modelopt/torch/trace/__init__.py +25 -0
  238. modelopt/torch/trace/analyzer.py +1368 -0
  239. modelopt/torch/trace/modules/__init__.py +19 -0
  240. modelopt/torch/trace/modules/concat.py +384 -0
  241. modelopt/torch/trace/modules/nn.py +153 -0
  242. modelopt/torch/trace/plugins/__init__.py +34 -0
  243. modelopt/torch/trace/plugins/megatron.py +36 -0
  244. modelopt/torch/trace/plugins/transformers.py +58 -0
  245. modelopt/torch/trace/symbols.py +545 -0
  246. modelopt/torch/trace/tracer.py +331 -0
  247. modelopt/torch/utils/__init__.py +28 -0
  248. modelopt/torch/utils/_pytree.py +133 -0
  249. modelopt/torch/utils/cpp_extension.py +91 -0
  250. modelopt/torch/utils/dataset_utils.py +484 -0
  251. modelopt/torch/utils/distributed.py +311 -0
  252. modelopt/torch/utils/graph.py +123 -0
  253. modelopt/torch/utils/image_processor.py +112 -0
  254. modelopt/torch/utils/import_utils.py +35 -0
  255. modelopt/torch/utils/list.py +54 -0
  256. modelopt/torch/utils/logging.py +127 -0
  257. modelopt/torch/utils/memory_monitor.py +146 -0
  258. modelopt/torch/utils/network.py +658 -0
  259. modelopt/torch/utils/perf.py +174 -0
  260. modelopt/torch/utils/plugins/__init__.py +27 -0
  261. modelopt/torch/utils/plugins/megatron_generate.py +299 -0
  262. modelopt/torch/utils/plugins/megatron_mmlu.py +152 -0
  263. modelopt/torch/utils/plugins/megatron_preprocess_data.py +200 -0
  264. modelopt/torch/utils/random.py +163 -0
  265. modelopt/torch/utils/speech_dataset_utils.py +134 -0
  266. modelopt/torch/utils/tensor.py +87 -0
  267. modelopt/torch/utils/vlm_dataset_utils.py +110 -0
  268. nvidia_modelopt-0.35.0.dist-info/METADATA +171 -0
  269. nvidia_modelopt-0.35.0.dist-info/RECORD +272 -0
  270. nvidia_modelopt-0.35.0.dist-info/WHEEL +5 -0
  271. nvidia_modelopt-0.35.0.dist-info/licenses/LICENSE +14 -0
  272. nvidia_modelopt-0.35.0.dist-info/top_level.txt +1 -0
modelopt/__init__.py ADDED
@@ -0,0 +1,20 @@
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
+ from importlib.metadata import version as _version
19
+
20
+ __version__ = _version("nvidia-modelopt")
@@ -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,30 @@
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 import tensorrt_llm
21
+ try:
22
+ import tensorrt_llm
23
+ except ImportError:
24
+ print(
25
+ "tensorrt_llm package is not installed. Please build or install tensorrt_llm package"
26
+ " properly before calling the llm deployment API."
27
+ )
28
+ raise
29
+
30
+ from .generate import *
@@ -0,0 +1,345 @@
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
+ import warnings
20
+ from collections.abc import Iterable
21
+ from pathlib import Path
22
+ from typing import Any
23
+
24
+ import torch
25
+ from tensorrt_llm import SamplingParams
26
+ from tensorrt_llm.bindings.executor import DecodingConfig
27
+
28
+ try:
29
+ from tensorrt_llm.llmapi import CudaGraphConfig
30
+ from tensorrt_llm.llmapi import KvCacheConfig as TRT_KvCacheConfig
31
+ from tensorrt_llm.llmapi.llm import _TorchLLM, _TrtLLM
32
+ from tensorrt_llm.llmapi.tokenizer import TokenizerBase, TransformersTokenizer
33
+ except ImportError:
34
+ print("Please upgrade tensorrt-llm to 1.0.0rc or later")
35
+ raise
36
+
37
+
38
+ def _sanitize_temperature_and_top_p(temperature, top_p):
39
+ assert temperature >= 0.0, "Temperature must be greater than 0.0."
40
+
41
+ # TRT LLM accepts temperature values only greater than 0.0
42
+ temperature = max(temperature, 0.001)
43
+
44
+ kwargs = {"temperature": temperature}
45
+ if top_p is not None:
46
+ # cpp executor only supports topP.value() > 0.f
47
+ top_p = 1e-4 if top_p == 0 else top_p
48
+ kwargs["top_p"] = top_p
49
+
50
+ return kwargs
51
+
52
+
53
+ class LLM:
54
+ """A wrapper over the ``tensorrt_llm.llmapi.llm.LLM`` for LLM profiling and validation."""
55
+
56
+ def _build_trt_llm_from_config(
57
+ self, config, engine_dir, tokenizer, kv_cache_config, medusa_choices, max_batch_size
58
+ ):
59
+ build_config = config["build_config"]
60
+ world_size = config.get("pretrained_config", {}).get("mapping", {}).get("world_size", 1)
61
+ max_batch_size = max(max_batch_size, build_config["max_batch_size"])
62
+ max_tokens_kv_cache = build_config["max_seq_len"] * max_batch_size
63
+
64
+ trt_kv_cache_config = TRT_KvCacheConfig(enable_block_reuse=False)
65
+
66
+ # If not specified, free_gpu_memory_fraction is set to the default TRT LLM value 0.9
67
+ trt_kv_cache_config.free_gpu_memory_fraction = kv_cache_config.get(
68
+ "free_gpu_memory_fraction", 0.9
69
+ )
70
+
71
+ # If not specified, max_tokens is set to the max value calculated above.
72
+ trt_kv_cache_config.max_tokens = kv_cache_config.get("max_tokens", max_tokens_kv_cache)
73
+
74
+ kwargs = {}
75
+ if medusa_choices is not None:
76
+ decoding_config = DecodingConfig()
77
+ decoding_config.medusa_choices = medusa_choices
78
+ kwargs["decoding_config"] = decoding_config
79
+ assert world_size == 1, "decoding_config does not support multi TP in HLAPI."
80
+
81
+ if tokenizer is None:
82
+ # Assume the tokenizer is stored in the engine_dir if not specified.
83
+ tokenizer = engine_dir
84
+
85
+ # CustomSentencePieceTokenizer will not be recognized by llmapi, wrapping it around TransformersTokenizer
86
+ if type(tokenizer).__name__ in ["CustomSentencePieceTokenizer"]:
87
+ tokenizer = TransformersTokenizer(tokenizer)
88
+
89
+ self.llm = _TrtLLM(
90
+ backend=None,
91
+ model=engine_dir,
92
+ tokenizer=tokenizer,
93
+ kv_cache_config=trt_kv_cache_config,
94
+ **kwargs,
95
+ )
96
+
97
+ def _build_torch_llm_from_config(
98
+ self, checkpoint_dir, tokenizer, tp, trust_remote_code, max_batch_size
99
+ ):
100
+ kwargs = {}
101
+ if tokenizer is not None:
102
+ kwargs["tokenizer"] = tokenizer
103
+
104
+ if tp < 1:
105
+ tp = torch.cuda.device_count()
106
+
107
+ # Sometimes 90% of the GPU memory is not enough for the TRT LLM torch engine.
108
+ trt_kv_cache_config = TRT_KvCacheConfig(
109
+ enable_block_reuse=False, free_gpu_memory_fraction=0.85
110
+ )
111
+
112
+ cuda_graph_config = None
113
+ if max_batch_size > 0:
114
+ cuda_graph_config = CudaGraphConfig(
115
+ batch_sizes=[2**i for i in range(int((max_batch_size - 1).bit_length()))]
116
+ + [max_batch_size],
117
+ max_batch_size=max_batch_size,
118
+ enable_padding=True,
119
+ )
120
+
121
+ self.llm = _TorchLLM(
122
+ backend="pytorch",
123
+ model=checkpoint_dir,
124
+ tensor_parallel_size=tp,
125
+ trust_remote_code=trust_remote_code,
126
+ enable_chunked_prefill=True,
127
+ kv_cache_config=trt_kv_cache_config,
128
+ # pytorch backend configs
129
+ cuda_graph_config=cuda_graph_config,
130
+ **kwargs,
131
+ )
132
+
133
+ def __init__(
134
+ self,
135
+ checkpoint_dir: str | Path,
136
+ tokenizer: "str | Path | TokenizerBase | None" = None,
137
+ kv_cache_config: dict[str, int | float] = {},
138
+ medusa_choices: Any = None,
139
+ tp: int = 0,
140
+ trust_remote_code: bool = False,
141
+ max_batch_size: int = 0,
142
+ ):
143
+ """Initializes the LLM runner class.
144
+
145
+ Args:
146
+ engine_dir: the directory path of the TensorRT-LLM engine.
147
+ tokenizer: the tokenizer. For example, a tokenizer from the Huggingface model.
148
+ kv_cache_config: the kv cache config as a dict. Please refer to
149
+ https://nvidia.github.io/TensorRT-LLM/performance/performance-tuning-guide/
150
+ medusa_choices: The medusa choices for the decoding config.
151
+ tp: the tensor parallel size (for the torch backend). If 0, it will be set to the number of GPUs.
152
+ trust_remote_code: whether to trust the remote code (for the torch backend).
153
+ max_batch_size: Max batch size for the LLM backend. If 0, it will be set to the max batch size
154
+ in the engine config.
155
+ """
156
+ with open(Path(checkpoint_dir) / "config.json") as config_file:
157
+ config = json.load(config_file)
158
+
159
+ if "build_config" in config:
160
+ self._is_torch = False
161
+ self._build_trt_llm_from_config(
162
+ config,
163
+ checkpoint_dir,
164
+ tokenizer,
165
+ kv_cache_config,
166
+ medusa_choices,
167
+ max_batch_size,
168
+ )
169
+
170
+ self._max_seq_len = self.llm.args.build_config.max_seq_len
171
+ self._max_beam_width = self.llm.args.build_config.max_beam_width
172
+ self._gather_context_logits = self.llm.args.build_config.gather_context_logits
173
+ else:
174
+ self._is_torch = True
175
+ assert medusa_choices is None, (
176
+ "medusa_choices is not supported with the torch llmapi"
177
+ )
178
+
179
+ self._build_torch_llm_from_config(
180
+ checkpoint_dir, tokenizer, tp, trust_remote_code, max_batch_size
181
+ )
182
+
183
+ def _find_max_position_embeddings(cfg: dict) -> int | None:
184
+ if "max_position_embeddings" in cfg:
185
+ return cfg["max_position_embeddings"]
186
+ for v in cfg.values():
187
+ if isinstance(v, dict):
188
+ res = _find_max_position_embeddings(v)
189
+ if res is not None:
190
+ return res
191
+ return None
192
+
193
+ # Some VLMs may have a sub-config for max_position_embeddings, so we need to find it.
194
+ self._max_seq_len = _find_max_position_embeddings(config)
195
+ if self._max_seq_len is None:
196
+ warnings.warn(
197
+ "max_position_embeddings not found in config.json, using default value 8192"
198
+ )
199
+ self._max_seq_len = 8192
200
+ else:
201
+ print(f"max_position_embeddings: {self._max_seq_len}")
202
+ self._max_beam_width = 1
203
+ self._gather_context_logits = False
204
+
205
+ @property
206
+ def max_seq_len(self):
207
+ """Get the max sequence length from the LLM instance."""
208
+ return self._max_seq_len
209
+
210
+ @property
211
+ def max_beam_width(self):
212
+ """Get the max beam width from the LLM instance."""
213
+ return self._max_beam_width
214
+
215
+ @property
216
+ def gather_context_logits(self):
217
+ """Returns whether the context_logits can be returned from the LLM instance."""
218
+ return self._gather_context_logits
219
+
220
+ def _generate(
221
+ self,
222
+ prompts: Iterable[str] | Iterable[list[int]],
223
+ max_new_tokens: int,
224
+ temperature: float = 1.0,
225
+ top_p: float | None = None,
226
+ stop_words: list[str] | None = None,
227
+ ):
228
+ assert temperature >= 0.0, "Temperature must be greater than 0.0."
229
+
230
+ # TODO: Remove this once torch backend supports stop words
231
+ if self._is_torch:
232
+ stop_words = None
233
+
234
+ beam_width = self.max_beam_width
235
+ kwargs = _sanitize_temperature_and_top_p(temperature, top_p)
236
+ sampling_config = SamplingParams(
237
+ max_tokens=max_new_tokens,
238
+ use_beam_search=True,
239
+ best_of=beam_width,
240
+ stop=stop_words,
241
+ **kwargs,
242
+ )
243
+
244
+ return self.llm.generate(prompts, sampling_params=sampling_config, use_tqdm=False)
245
+
246
+ def generate_tokens(
247
+ self,
248
+ prompts: Iterable[str] | Iterable[list[int]],
249
+ max_new_tokens: int,
250
+ temperature: float = 1.0,
251
+ top_p: float | None = None,
252
+ stop_words: list[str] | None = None,
253
+ ) -> list[list[int]] | list[list[list[int]]]:
254
+ """Generates the tokens based on the input prompts.
255
+
256
+ Args:
257
+ prompts: The input prompts. Could be a list of strings or token lists.
258
+ max_new_tokens: The max output token length.
259
+ temperature: The sampling temperature.
260
+ top_p: The nucleus sampling parameter.
261
+ stop_words: A list of words that the generate stops on.
262
+
263
+ Returns:
264
+ a list of output token lists if max_beam_width is 1 or a 3D list with shape [batch, beam, sequence_len].
265
+ """
266
+ outputs = self._generate(prompts, max_new_tokens, temperature, top_p, stop_words)
267
+ output_tokens = []
268
+
269
+ beam_width = self.max_beam_width
270
+ for request_output in outputs:
271
+ token_ids = [
272
+ completion_output.token_ids for completion_output in request_output.outputs
273
+ ]
274
+ if beam_width == 1:
275
+ # each output_text is a single list of tokens.
276
+ output_tokens += token_ids
277
+ else:
278
+ # each output_text is a list of beam searched token lists.
279
+ output_tokens.append(token_ids)
280
+
281
+ return output_tokens
282
+
283
+ def generate_text(
284
+ self,
285
+ prompts: Iterable[str] | Iterable[list[int]],
286
+ max_new_tokens: int,
287
+ temperature: float = 1.0,
288
+ top_p: float | None = None,
289
+ stop_words: list[str] | None = None,
290
+ ) -> list[str] | list[list[str]]:
291
+ """Generates the text based on the input prompts.
292
+
293
+ Args:
294
+ prompts: The input prompts. Could be a list of strings or token lists.
295
+ max_new_tokens: The max output token length.
296
+ temperature: The sampling temperature
297
+ stop_words: A list of words the generate will stop on.
298
+
299
+ Returns:
300
+ a list of output text strings if max_beam_width is 1 or a 2D list with shape [batch, beam].
301
+ """
302
+ outputs = self._generate(prompts, max_new_tokens, temperature, top_p, stop_words)
303
+ output_texts = []
304
+
305
+ beam_width = self.max_beam_width
306
+ for request_output in outputs:
307
+ texts = [completion_output.text for completion_output in request_output.outputs]
308
+ if beam_width == 1:
309
+ # each output_text is a single text string.
310
+ output_texts += texts
311
+ else:
312
+ # each output_text is a list of beam searched texts
313
+ output_texts.append(texts)
314
+
315
+ return output_texts
316
+
317
+ def generate_context_logits(
318
+ self,
319
+ prompts: Iterable[str] | Iterable[list[int]],
320
+ temperature: float = 1.0,
321
+ top_p: float | None = None,
322
+ ) -> list[torch.tensor]:
323
+ """Generates the context logits based on the input prompts.
324
+
325
+ Args:
326
+ prompts: The input prompts. Could be a list of strings or token lists.
327
+ temperature: The sampling temperature.
328
+ top_p: The nucleus sampling parameter.
329
+
330
+ Returns:
331
+ a tensor list of the context_logits.
332
+ """
333
+ assert self.gather_context_logits, (
334
+ "Please enable gather_context_logits flag when building the engine."
335
+ )
336
+ assert temperature >= 0.0, "Temperature must be greater than 0.0."
337
+
338
+ kwargs = _sanitize_temperature_and_top_p(temperature, top_p)
339
+ kwargs["return_context_logits"] = True
340
+
341
+ sampling_config = SamplingParams(max_tokens=1, use_beam_search=True, best_of=1, **kwargs)
342
+
343
+ outputs = self.llm.generate(prompts, sampling_params=sampling_config, use_tqdm=False)
344
+
345
+ return [output.context_logits for output in outputs]
@@ -0,0 +1,34 @@
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
+
20
+ MIN_PYTHON_VERSION = (3, 10)
21
+
22
+ try:
23
+ from . import quantization
24
+ from .logging_config import configure_logging, logger
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
+ logger.warning(
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
+ )
@@ -0,0 +1,19 @@
1
+ # SPDX-FileCopyrightText: Copyright (c) 2025 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
+ """AutoCast package for converting FP32 ONNX models to mixed precision."""
17
+
18
+ from .convert import convert_to_f16, convert_to_mixed_precision
19
+ from .logging_config import configure_logging
@@ -0,0 +1,187 @@
1
+ #!/usr/bin/env python3
2
+
3
+ # SPDX-FileCopyrightText: Copyright (c) 2025 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
4
+ # SPDX-License-Identifier: Apache-2.0
5
+ #
6
+ # Licensed under the Apache License, Version 2.0 (the "License");
7
+ # you may not use this file except in compliance with the License.
8
+ # You may obtain a copy of the License at
9
+ #
10
+ # http://www.apache.org/licenses/LICENSE-2.0
11
+ #
12
+ # Unless required by applicable law or agreed to in writing, software
13
+ # distributed under the License is distributed on an "AS IS" BASIS,
14
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15
+ # See the License for the specific language governing permissions and
16
+ # limitations under the License.
17
+
18
+ # SPDX-FileCopyrightText: Copyright (c) 2025 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
19
+ # SPDX-License-Identifier: Apache-2.0
20
+ #
21
+ # Licensed under the Apache License, Version 2.0 (the "License");
22
+ # you may not use this file except in compliance with the License.
23
+ # You may obtain a copy of the License at
24
+ #
25
+ # http://www.apache.org/licenses/LICENSE-2.0
26
+ #
27
+ # Unless required by applicable law or agreed to in writing, software
28
+ # distributed under the License is distributed on an "AS IS" BASIS,
29
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
30
+ # See the License for the specific language governing permissions and
31
+ # limitations under the License.
32
+
33
+ """This module provides the command line interface (CLI) entry point for AutoCast."""
34
+
35
+ import argparse
36
+ import sys
37
+
38
+ from modelopt.onnx import utils as onnx_utils
39
+ from modelopt.onnx.autocast.convert import (
40
+ DEFAULT_DATA_MAX,
41
+ DEFAULT_INIT_MAX,
42
+ convert_to_mixed_precision,
43
+ )
44
+ from modelopt.onnx.autocast.logging_config import configure_logging, logger
45
+
46
+
47
+ def get_parser() -> argparse.ArgumentParser:
48
+ """Get the argument parser for AutoCast."""
49
+ parser = argparse.ArgumentParser()
50
+ parser.add_argument("--onnx_path", type=str, required=True, help="Path to the ONNX model")
51
+ parser.add_argument(
52
+ "--output_path",
53
+ type=str,
54
+ help="Output filename to save the converted ONNX model. If None, save it in the same dir as "
55
+ "the original ONNX model with an appropriate suffix.",
56
+ )
57
+ parser.add_argument(
58
+ "--low_precision_type",
59
+ "-t",
60
+ type=str,
61
+ default="fp16",
62
+ help="Precision to reduce to",
63
+ choices=["fp16", "bf16"],
64
+ )
65
+ parser.add_argument(
66
+ "--calibration_data",
67
+ "-d",
68
+ type=str,
69
+ help="File path to inputs for reference runner, either NPZ or Polygraphy JSON file. "
70
+ "If not provided, random inputs will be used",
71
+ )
72
+ parser.add_argument(
73
+ "--nodes_to_exclude",
74
+ "-n",
75
+ type=str,
76
+ nargs="*",
77
+ default=[],
78
+ help="List of regex patterns to match node names that should remain in FP32",
79
+ )
80
+ parser.add_argument(
81
+ "--op_types_to_exclude",
82
+ "-op",
83
+ type=str,
84
+ nargs="*",
85
+ default=[],
86
+ help="List of op types that should remain in FP32",
87
+ )
88
+ parser.add_argument(
89
+ "--data_max",
90
+ type=float,
91
+ default=DEFAULT_DATA_MAX,
92
+ help="Maximum absolute value for node outputs, nodes with outputs greater than this value will remain in FP32",
93
+ )
94
+ parser.add_argument(
95
+ "--init_max",
96
+ type=float,
97
+ default=DEFAULT_INIT_MAX,
98
+ help="Maximum absolute value for initializers, nodes with initializers greater than this value will remain in "
99
+ "FP32",
100
+ )
101
+ parser.add_argument(
102
+ "--init_conversion_max_bytes",
103
+ type=int,
104
+ help="Maximum size in bytes for initializer conversion. Larger initializers will be cast at runtime.",
105
+ )
106
+ parser.add_argument(
107
+ "--max_depth_of_reduction",
108
+ type=int,
109
+ help="Maximum depth of reduction allowed in low precision. Nodes with higher reduction depths will remain in "
110
+ "FP32. If not provided, infinity will be used.",
111
+ )
112
+ parser.add_argument(
113
+ "--keep_io_types",
114
+ action="store_true",
115
+ help="Keep the input and output types of the model, otherwise they will be converted to FP16",
116
+ )
117
+ parser.add_argument(
118
+ "--log_level",
119
+ type=str,
120
+ default="INFO",
121
+ help="Log level",
122
+ choices=["DEBUG", "INFO", "WARNING", "ERROR", "CRITICAL"],
123
+ )
124
+ parser.add_argument(
125
+ "--providers",
126
+ type=str,
127
+ default=["cpu"],
128
+ nargs="+",
129
+ help=(
130
+ "List of Execution Providers (EPs) for ONNX-Runtime backend. "
131
+ "Any subset of ['trt', 'cuda:x', 'cpu'], where 'x' is the device id. "
132
+ "If a custom op is detected in the model, 'trt' will automatically be added to the EP list."
133
+ ),
134
+ )
135
+ parser.add_argument(
136
+ "--trt_plugins",
137
+ type=str,
138
+ default=[],
139
+ nargs="+",
140
+ help=(
141
+ "List of custom TensorRT plugin library paths in .so format (compiled shared library). "
142
+ "If this a non-empty list, the TensorrtExecutionProvider is invoked, so make sure that the TensorRT "
143
+ "libraries are in the PATH or LD_LIBRARY_PATH variables."
144
+ ),
145
+ )
146
+
147
+ return parser
148
+
149
+
150
+ def main(argv=None):
151
+ """Main entry point for AutoCast command line interface.
152
+
153
+ Args:
154
+ argv: List of command line arguments.
155
+
156
+ Returns:
157
+ onnx.ModelProto: The converted mixed precision model.
158
+ """
159
+ parser = get_parser()
160
+ args = parser.parse_args(argv)
161
+ configure_logging(args.log_level)
162
+ model_out = convert_to_mixed_precision(
163
+ onnx_path=args.onnx_path,
164
+ low_precision_type=args.low_precision_type,
165
+ nodes_to_exclude=args.nodes_to_exclude,
166
+ op_types_to_exclude=args.op_types_to_exclude,
167
+ data_max=args.data_max,
168
+ init_max=args.init_max,
169
+ keep_io_types=args.keep_io_types,
170
+ calibration_data=args.calibration_data,
171
+ init_conversion_max_bytes=args.init_conversion_max_bytes,
172
+ providers=args.providers,
173
+ trt_plugins=args.trt_plugins,
174
+ max_depth_of_reduction=args.max_depth_of_reduction,
175
+ )
176
+
177
+ output_path = args.output_path
178
+ if output_path is None:
179
+ output_path = args.onnx_path.replace(".onnx", f".{args.low_precision_type}.onnx")
180
+
181
+ onnx_utils.save_onnx(model_out, output_path)
182
+ logger.info(f"Converted model saved to {output_path}")
183
+ return model_out
184
+
185
+
186
+ if __name__ == "__main__":
187
+ main(sys.argv[1:])