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
@@ -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
+ """Code from TRT-LLM that export optimized models to the TensorRT-LLM checkpoint."""
17
+
18
+ from enum import IntEnum
19
+
20
+
21
+ # These clasess are directly copied from TRT-LLM to relex TRT-LLM dependency for checkpoint export
22
+ class LayerNormType(IntEnum):
23
+ """LayerNormType from tensorrt_llm.functional."""
24
+
25
+ LayerNorm = 0
26
+ RmsNorm = 1
27
+ GroupNorm = 2
28
+
29
+
30
+ class LayerNormPositionType(IntEnum):
31
+ """LayerNormPositionType from tensorrt_llm.functional."""
32
+
33
+ pre_layernorm = 0
34
+ post_layernorm = 1
35
+
36
+
37
+ class MLPType(IntEnum):
38
+ """MLPType from tensorrt_llm.functional."""
39
+
40
+ MLP = 0
41
+ GatedMLP = 1
42
+ FusedGatedMLP = 2
@@ -0,0 +1,405 @@
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
+ """Utils for TensorRT-LLM checkpoint export.
17
+
18
+ Some of the logics in this file are empirical and needs constant update if exceptions occur.
19
+ """
20
+
21
+ import logging
22
+ from pathlib import Path
23
+ from typing import TYPE_CHECKING, Any
24
+ from warnings import warn
25
+
26
+ from .layer_utils import model_type_is_enc_dec
27
+ from .tensorrt_llm_type import LayerNormPositionType, LayerNormType, MLPType
28
+
29
+ if TYPE_CHECKING:
30
+ from transformers import T5Config
31
+
32
+ from modelopt import __version__
33
+
34
+ from .model_config import (
35
+ LAYERNORM_DEFAULT,
36
+ LAYERNORM_RMS,
37
+ QUANTIZATION_NONE,
38
+ DecoderLayerConfig,
39
+ MLPConfig,
40
+ ModelConfig,
41
+ )
42
+
43
+ logger = logging.getLogger(__name__)
44
+
45
+ # For NEMO and ENC/DEC models where the TensorRT-LLM model architecture and HF config are not aligned.
46
+ MODEL_NAME_TO_HF_ARCH_MAP = {
47
+ "llama": "LlamaForCausalLM",
48
+ "gemma": "GemmaForCausalLM",
49
+ "gemma3": "Gemma3ForCausalLM",
50
+ "gpt": "GPTForCausalLM",
51
+ "enc": "EncoderModel",
52
+ "dec": "DecoderModel",
53
+ "mllama": "MLLaMAModel",
54
+ "whisper_encoder": "WhisperEncoder",
55
+ }
56
+
57
+
58
+ def is_tensorrt_llm_0_8_or_9():
59
+ """Returns true if tensorrt_llm version is 0.8 or 0.9."""
60
+ try:
61
+ import tensorrt_llm
62
+
63
+ return tensorrt_llm.__version__.startswith(("0.8", "0.9"))
64
+ except Exception:
65
+ return False
66
+
67
+
68
+ def _find_layernorm_type(model_config: ModelConfig):
69
+ if model_config.ln_f:
70
+ return model_config.ln_f.layernorm_type
71
+ for layer in model_config.layers:
72
+ if layer.input_layernorm:
73
+ return layer.input_layernorm.layernorm_type
74
+ if layer.post_layernorm:
75
+ return layer.post_layernorm.layernorm_type
76
+ return LAYERNORM_DEFAULT
77
+
78
+
79
+ def convert_to_tensorrt_llm_config(
80
+ model_config: ModelConfig,
81
+ quant_config: dict[str, Any],
82
+ hf_config=None,
83
+ ):
84
+ """Convert to TensorRT-LLM checkpoint config.
85
+
86
+ Args:
87
+ model_config: The model_config to convert.
88
+ quant_config: The quantization config to convert. It will be updated with kv_cache_quant_algo.
89
+ hf_config: The huggingface model config.
90
+ If provided, we try to use the TensorRT-LLM's export method if available.
91
+ """
92
+ tp_size = model_config.tensor_parallel
93
+ pp_size = model_config.pipeline_parallel
94
+
95
+ first_attention_config = None
96
+ first_attention_decoder_config = None
97
+ first_mlp_decoder_config = None
98
+ for decoder_layer in model_config.layers:
99
+ first_attention_config = (
100
+ decoder_layer.attention or decoder_layer.self_attention or decoder_layer.cross_attention
101
+ )
102
+ if first_attention_config and not first_attention_decoder_config:
103
+ first_attention_decoder_config = decoder_layer
104
+
105
+ first_mlp_decoder_config = decoder_layer if decoder_layer.mlp else None
106
+
107
+ if first_attention_decoder_config and first_mlp_decoder_config:
108
+ break
109
+
110
+ assert (
111
+ first_attention_config is not None
112
+ and first_attention_decoder_config is not None
113
+ and first_mlp_decoder_config is not None
114
+ ), "Model must have at least one attention block and one MLP block"
115
+
116
+ mapping = {
117
+ "world_size": tp_size * pp_size,
118
+ "tp_size": tp_size,
119
+ "pp_size": pp_size,
120
+ }
121
+
122
+ decoder_type = model_config.layers[0].decoder_type
123
+
124
+ config_architecture = model_config.architecture
125
+ if not config_architecture:
126
+ config_architecture = MODEL_NAME_TO_HF_ARCH_MAP[decoder_type]
127
+ # For Encoder-Decoder model
128
+ is_enc_dec = model_type_is_enc_dec(decoder_type)
129
+ if is_enc_dec:
130
+ # For encoder
131
+ if model_config.enc_dec == "enc":
132
+ config_architecture = MODEL_NAME_TO_HF_ARCH_MAP[
133
+ f"{decoder_type}_encoder" if decoder_type in ["whisper"] else "enc"
134
+ ]
135
+ # For decoder
136
+ else:
137
+ config_architecture = MODEL_NAME_TO_HF_ARCH_MAP["dec"]
138
+
139
+ config = {
140
+ "producer": {
141
+ "name": "modelopt",
142
+ "version": __version__,
143
+ },
144
+ "architecture": config_architecture,
145
+ "dtype": model_config.dtype,
146
+ "logits_dtype": "float16" if model_config.dtype == "bfloat16" else model_config.dtype,
147
+ "num_hidden_layers": len(model_config.layers) * pp_size,
148
+ "num_attention_heads": model_config.num_attention_heads,
149
+ "num_key_value_heads": model_config.num_kv_heads,
150
+ "hidden_size": first_mlp_decoder_config.hidden_size,
151
+ "norm_epsilon": (
152
+ first_attention_decoder_config.mlp_layernorm.eps
153
+ if is_enc_dec
154
+ else first_attention_decoder_config.input_layernorm.eps
155
+ ),
156
+ "vocab_size": model_config.vocab_size,
157
+ "max_position_embeddings": model_config.max_position_embeddings,
158
+ "hidden_act": first_mlp_decoder_config.mlp.hidden_act,
159
+ "use_parallel_embedding": True,
160
+ "embedding_sharding_dim": 0,
161
+ "head_size": first_attention_decoder_config.attention_head_size,
162
+ "intermediate_size": first_mlp_decoder_config.ffn_hidden_size_local * tp_size,
163
+ "position_embedding_type": (
164
+ "alibi"
165
+ if first_attention_decoder_config.use_alibi
166
+ else (
167
+ first_attention_decoder_config.position_embedding_type
168
+ if first_attention_decoder_config.position_embedding_type
169
+ else "rope_gpt_neox"
170
+ )
171
+ ),
172
+ "share_embedding_table": bool(model_config.lm_head is None and pp_size == 1),
173
+ "residual_mlp": first_attention_decoder_config.residual_mlp is not None,
174
+ # Model Optimizer customized fields
175
+ "bias": first_attention_config.dense.bias is not None,
176
+ "rotary_pct": first_attention_decoder_config.rotary_pct,
177
+ "rank": model_config.rank,
178
+ "decoder": first_attention_decoder_config.decoder_type,
179
+ "rmsnorm": _find_layernorm_type(model_config) == LAYERNORM_RMS,
180
+ "lm_head_bias": model_config.lm_head is not None and model_config.lm_head.bias is not None,
181
+ }
182
+
183
+ # Update quantization config
184
+ if model_config.quantization != QUANTIZATION_NONE:
185
+ # In TRT LLM, the embedding table is shared for the following models, so lm_head quantization format
186
+ # won't be automatically detected in the excluded_modules. We need to manually add it to the exclusions.
187
+ share_embedding_table = model_config.lm_head is None and pp_size == 1
188
+ if share_embedding_table:
189
+ quant_config.setdefault("exclude_modules", []).append("lm_head")
190
+
191
+ quant_config["kv_cache_quant_algo"] = first_attention_config.kv_cache_dtype
192
+
193
+ if hf_config is not None:
194
+ try:
195
+ from tensorrt_llm.models import MODEL_MAP
196
+ from tensorrt_llm.models.modeling_utils import Mapping, QuantConfig
197
+
198
+ model_cls = MODEL_MAP[config_architecture]
199
+ config_cls = getattr(model_cls, "config_class", None)
200
+
201
+ if config_cls is not None:
202
+ tensorrt_llm_config = config_cls.from_hugging_face(
203
+ hf_config_or_dir=hf_config,
204
+ dtype=model_config.dtype,
205
+ mapping=Mapping.from_dict(mapping),
206
+ quant_config=QuantConfig.from_dict(
207
+ {k: v for k, v in quant_config.items() if k != "quantized_layers"}
208
+ ),
209
+ ).to_dict()
210
+
211
+ config.update(tensorrt_llm_config)
212
+ # Modelopt uses parallel_embedding by default.
213
+ config.update(
214
+ {
215
+ "use_parallel_embedding": True,
216
+ "embedding_sharding_dim": 0,
217
+ "logits_dtype": "float16"
218
+ if model_config.dtype == "bfloat16"
219
+ else model_config.dtype,
220
+ }
221
+ )
222
+
223
+ return config
224
+
225
+ except Exception as e:
226
+ warn(
227
+ "Cannot export tensorrt_llm checkpoint config due to the following error. "
228
+ f"Trying the manual approach: \n{e}"
229
+ )
230
+
231
+ if first_attention_decoder_config.rotary_base:
232
+ config["rotary_base"] = first_attention_decoder_config.rotary_base
233
+
234
+ if first_attention_decoder_config.rope_scaling:
235
+ config["rotary_scaling"] = first_attention_decoder_config.rope_scaling
236
+
237
+ config["mapping"] = mapping
238
+ config["quantization"] = quant_config
239
+
240
+ layernorm_type_map = {i.name: i.value for i in LayerNormType}
241
+ layernorm_position_map = {i.name: i.value for i in LayerNormPositionType}
242
+
243
+ if decoder_type in ["gpt", "gemma", "llama"]:
244
+ pass
245
+ elif decoder_type == "mpt":
246
+ config.update(
247
+ {
248
+ "clip_qkv": first_attention_config.clip_qkv,
249
+ "alibi_bias_max": model_config.layers[0].alibi_bias_max,
250
+ }
251
+ )
252
+ elif decoder_type == "recurrentgemma":
253
+ config["conv_kernel"] = 4
254
+ config["state_size"] = 1
255
+ config["state_dtype"] = "float32"
256
+ config["rnn_hidden_size"] = model_config.layers[0].rnn_hidden_size
257
+ config["rnn_conv_dim_size"] = model_config.layers[0].rnn_hidden_size
258
+ config["logits_soft_cap"] = model_config.layers[0].logits_soft_cap
259
+ config["emb_scale_by_sqrt_dim"] = model_config.layers[0].emb_scale_by_sqrt_dim
260
+ config["layer_types"] = model_config.layers[0].layer_types
261
+ elif is_enc_dec:
262
+ if decoder_type in ["whisper"]:
263
+ config["n_mels"] = hf_config.num_mel_bins
264
+ model_is_multilingual = hf_config.vocab_size >= 51865
265
+ num_languages = hf_config.vocab_size - 51765 - int(model_is_multilingual)
266
+ config["num_languages"] = num_languages
267
+
268
+ # T5 models use relative position embedding
269
+ # Bart models use learned_absolute position embedding
270
+ config["position_embedding_type"] = (
271
+ "relative" if decoder_type == "t5" else "learned_absolute"
272
+ )
273
+ config["share_embedding_table"] = getattr(model_config, "share_embedding_table")
274
+ config["has_position_embedding"] = bool(getattr(model_config, "position_embedding"))
275
+ # fallback to RmsNorm if not specified as HF might change class naming for layernorm
276
+ layernorm_type = model_config.layers[0].mlp_layernorm.layernorm_type
277
+ if not layernorm_type:
278
+ layernorm_type = "RmsNorm"
279
+ config["layernorm_type"] = layernorm_type_map[layernorm_type]
280
+ config["has_attention_qkvo_bias"] = bool(
281
+ model_config.layers[0].attention.qkv.bias is not None
282
+ if model_config.enc_dec == "enc"
283
+ else model_config.layers[0].self_attention.qkv.bias is not None
284
+ )
285
+ config["has_mlp_bias"] = model_config.layers[0].mlp.fc.bias is not None
286
+ config["has_model_final_layernorm"] = bool(model_config.ln_f)
287
+
288
+ mlp_type_map = {i.name: i.value for i in MLPType}
289
+
290
+ config["mlp_type"] = mlp_type_map[
291
+ (
292
+ "GatedMLP"
293
+ if isinstance(model_config.layers[0].mlp, MLPConfig)
294
+ and model_config.layers[0].mlp.gate
295
+ else "MLP"
296
+ )
297
+ ]
298
+ config["use_prompt_tuning"] = False
299
+ config["has_position_embedding"] = bool(model_config.position_embedding)
300
+ config["has_embedding_layernorm"] = bool(model_config.ln_embed)
301
+ config["has_embedding_scale"] = False
302
+ config["ffn_hidden_size"] = model_config.layers[0].mlp.fc.weight.shape[0]
303
+ # T5 uses q_scaling to offset attention scaling effect. Bart does not.
304
+ config["q_scaling"] = 1 / config["head_size"] ** 0.5 if decoder_type == "t5" else 1.0
305
+ config["layernorm_position"] = (
306
+ layernorm_position_map["post_layernorm"]
307
+ if decoder_type == "bart"
308
+ else layernorm_position_map["pre_layernorm"]
309
+ )
310
+ config["relative_attention"] = config["position_embedding_type"] == "relative"
311
+ config["max_distance"] = model_config.layers[0].rel_attn_max_distance
312
+ config["num_buckets"] = model_config.layers[0].rel_attn_num_buckets
313
+ config["model_type"] = decoder_type
314
+ config["use_parallel_embedding"] = True
315
+ config["use_implicit_relative_attention"] = False
316
+ if model_config.enc_dec == "dec":
317
+ config["rescale_before_lm_head"] = False
318
+ config["encoder_hidden_size"] = model_config.encoder_hidden_size
319
+ config["encoder_num_heads"] = model_config.encoder_num_heads
320
+ config["encoder_head_size"] = model_config.encoder_head_size
321
+ config["decoder_start_token_id"] = model_config.decoder_start_token_id
322
+ config["eos_token_id"] = model_config.eos_token_id
323
+ config["bos_token_id"] = model_config.bos_token_id
324
+ config["pad_token_id"] = model_config.pad_token_id
325
+ elif decoder_type == "dbrx":
326
+ config["clip_qkv"] = first_attention_decoder_config.clip_qkv
327
+
328
+ elif decoder_type == "mllama":
329
+ num_layers = config["num_hidden_layers"]
330
+ num_kv_heads = model_config.num_kv_heads
331
+ cross_attention_layers = set(model_config.layers[0].cross_attention_layers)
332
+
333
+ config["num_kv_heads_per_layer"] = [
334
+ 0 if i in cross_attention_layers else num_kv_heads for i in range(num_layers)
335
+ ]
336
+ config["num_kv_heads_per_cross_attn_layer"] = [
337
+ num_kv_heads if i in cross_attention_layers else 0 for i in range(num_layers)
338
+ ]
339
+
340
+ config["cross_attention"] = True
341
+ config["cross_attention_layers"] = model_config.layers[0].cross_attention_layers
342
+ config["embed_vocab_size"] = model_config.vocab_size + 8
343
+ vision_output_dim = model_config.layers[0].vision_output_dim
344
+ config["vision_output_dim"] = vision_output_dim if vision_output_dim != 0 else 7680
345
+ else:
346
+ raise NotImplementedError(
347
+ f"Cannot export tensorrt_llm checkpoint for model {decoder_type}: {config_architecture}. "
348
+ "It's not supported by TensorRT-LLM yet. Please try exporting the model to unified HF "
349
+ "checkpoint with ModelOpt and deploy the checkpoint with TensorRT-LLM pytorch backend."
350
+ )
351
+
352
+ # For Mixtral and Arctic
353
+ if first_attention_decoder_config.moe_num_experts:
354
+ config["moe"] = {
355
+ "num_experts": first_attention_decoder_config.moe_num_experts,
356
+ "top_k": first_attention_decoder_config.moe_top_k,
357
+ "normalization_mode": 1, # ExpertScaleNormalizationMode.RENORMALIZE
358
+ }
359
+
360
+ if decoder_type == "phi3":
361
+ config["moe"]["normalization_mode"] = 2 # ExpertScaleNormalizationMode.SPARSE_MIXER,
362
+ config["moe"]["sparse_mixer_epsilon"] = (
363
+ first_attention_decoder_config.sparse_mixer_epsilon
364
+ )
365
+
366
+ config["mapping"]["moe_tp_size"] = config["mapping"]["tp_size"]
367
+ config["mapping"]["moe_ep_size"] = 1
368
+
369
+ # Handle Medusa decoding
370
+ # TODO (chenhany): when inference pp > 1; only last pp has medusa heads
371
+ if model_config.medusa_heads is not None:
372
+ config["base_architecture"] = config["architecture"]
373
+ config["architecture"] = "MedusaForCausalLM"
374
+ # NOTE: max_draft_len is related to the medusa tree len. Currently it is hardcoded to 63.
375
+ config["max_draft_len"] = 63
376
+ config["num_medusa_heads"] = len(model_config.medusa_heads)
377
+ config["num_medusa_layers"] = len(model_config.medusa_heads[0].medusa_layers)
378
+
379
+ return config
380
+
381
+
382
+ def prepare_enc_dec_export_dir(tensorrt_llm_config: dict[str, Any], export_root: Path):
383
+ """Prepare the export directory for encoder-decoder model."""
384
+ # For encoder
385
+ if tensorrt_llm_config["architecture"] in ["EncoderModel", "WhisperEncoder"]:
386
+ export_dir = export_root.joinpath("encoder")
387
+ # For decoder
388
+ else:
389
+ export_dir = export_root.joinpath("decoder")
390
+ return export_dir
391
+
392
+
393
+ def prepare_t5_decoder_layer(
394
+ layer_config: DecoderLayerConfig,
395
+ model_config: "T5Config",
396
+ enc_dec: str,
397
+ layers: list[DecoderLayerConfig],
398
+ ):
399
+ """Prepare the config for each decoder layer of encoder-decoder model."""
400
+ layer_config.rel_attn_max_distance = model_config.relative_attention_max_distance
401
+ layer_config.rel_attn_num_buckets = model_config.relative_attention_num_buckets
402
+ if enc_dec == "enc" and layer_config.attention.rel_attn_table is None:
403
+ layer_config.attention.rel_attn_table = layers[0].attention.rel_attn_table
404
+ elif enc_dec == "dec" and layer_config.self_attention.rel_attn_table is None:
405
+ layer_config.self_attention.rel_attn_table = layers[0].self_attention.rel_attn_table
@@ -0,0 +1,94 @@
1
+ # Adapted from https://github.com/huggingface/accelerate/blob/c2f193a25c5449c0e34408bbbffa61ce420b00f6/
2
+ # src/accelerate/utils/transformer_engine.py
3
+
4
+ # Copyright 2021 The HuggingFace Team. All rights reserved.
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) 2024 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
+ """Convert the Model Optimizer quantized model to the transformer_engine."""
34
+
35
+ import torch
36
+ from torch import nn
37
+
38
+ __all__ = ["convert_to_transformer_engine"]
39
+
40
+
41
+ def _convert_model(model):
42
+ """Recursively converts the linear layers to their `transformers_engine` counterpart."""
43
+ import transformer_engine.pytorch as te
44
+
45
+ with te.fp8_model_init(enabled=True):
46
+ for name, module in model.named_children():
47
+ if type(module).__name__ == "QuantLinear":
48
+ # Return early if the linear layer weights are not multiples of 16
49
+ if any(p % 16 != 0 for p in module.weight.shape):
50
+ return
51
+ has_bias = module.bias is not None
52
+ te_module = te.Linear(
53
+ module.in_features,
54
+ module.out_features,
55
+ bias=has_bias,
56
+ params_dtype=module.weight.dtype,
57
+ )
58
+ te_module.weight.copy_(module.weight)
59
+ if has_bias:
60
+ te_module.bias.copy_(module.bias)
61
+
62
+ input_quantizer = module.input_quantizer
63
+ quant_max = input_quantizer.maxbound
64
+ input_scale_inv = input_quantizer.export_amax().float()[0] / quant_max
65
+ input_scale = 1 / input_scale_inv
66
+
67
+ weight_quantizer = module.weight_quantizer
68
+ quant_max = weight_quantizer.maxbound
69
+ weight_scale_inv = weight_quantizer.export_amax().float()[0] / quant_max
70
+ weight_scale = 1 / weight_scale_inv
71
+
72
+ # Update the TE layers with the Model Optimizer scaling factors
73
+ te_module.fp8_meta["scaling_fwd"].scale_inv[0].copy_(input_scale_inv)
74
+ te_module.fp8_meta["scaling_fwd"].scale_inv[1].copy_(weight_scale_inv)
75
+ te_module.fp8_meta["scaling_fwd"].scale[0].copy_(input_scale)
76
+ te_module.fp8_meta["scaling_fwd"].scale[1].copy_(weight_scale)
77
+
78
+ setattr(model, name, te_module)
79
+ else:
80
+ _convert_model(module)
81
+
82
+
83
+ def convert_to_transformer_engine(model: nn.Module):
84
+ """Converts the `Model Optimizer` quantized model to the `transformers_engine`."""
85
+ import transformer_engine.common.recipe as te_recipe
86
+ from transformer_engine.pytorch import fp8_autocast
87
+
88
+ with torch.no_grad():
89
+ _convert_model(model)
90
+
91
+ fp8_recipe = te_recipe.DelayedScaling()
92
+ model.forward = fp8_autocast(enabled=True, fp8_recipe=fp8_recipe)(model.forward)
93
+
94
+ return model