Register
Login
Resources
Docs Blog Datasets Glossary Case Studies Tutorials & Webinars
Product
Data Engine LLMs Platform Enterprise
Pricing Explore
Connect to our Discord channel

#20413 YOLOE: Fix visual prompt training

Merged
Ghost merged 1 commits into Ultralytics:main from ultralytics:yoloe-vp-fix
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
  1. # Ultralytics ๐Ÿš€ AGPL-3.0 License - https://ultralytics.com/license
  2. import json
  3. from pathlib import Path
  4. import torch
  5. from ultralytics.utils import IS_JETSON, LOGGER
  6. def export_onnx(
  7. torch_model,
  8. im,
  9. onnx_file,
  10. opset=14,
  11. input_names=["images"],
  12. output_names=["output0"],
  13. dynamic=False,
  14. ):
  15. """
  16. Exports a PyTorch model to ONNX format.
  17. Args:
  18. torch_model (torch.nn.Module): The PyTorch model to export.
  19. im (torch.Tensor): Example input tensor for the model.
  20. onnx_file (str): Path to save the exported ONNX file.
  21. opset (int): ONNX opset version to use for export.
  22. input_names (list): List of input tensor names.
  23. output_names (list): List of output tensor names.
  24. dynamic (bool | dict, optional): Whether to enable dynamic axes. Defaults to False.
  25. Notes:
  26. - Setting `do_constant_folding=True` may cause issues with DNN inference for torch>=1.12.
  27. """
  28. torch.onnx.export(
  29. torch_model,
  30. im,
  31. onnx_file,
  32. verbose=False,
  33. opset_version=opset,
  34. do_constant_folding=True, # WARNING: DNN inference with torch>=1.12 may require do_constant_folding=False
  35. input_names=input_names,
  36. output_names=output_names,
  37. dynamic_axes=dynamic or None,
  38. )
  39. def export_engine(
  40. onnx_file,
  41. engine_file=None,
  42. workspace=None,
  43. half=False,
  44. int8=False,
  45. dynamic=False,
  46. shape=(1, 3, 640, 640),
  47. dla=None,
  48. dataset=None,
  49. metadata=None,
  50. verbose=False,
  51. prefix="",
  52. ):
  53. """
  54. Exports a YOLO model to TensorRT engine format.
  55. Args:
  56. onnx_file (str): Path to the ONNX file to be converted.
  57. engine_file (str, optional): Path to save the generated TensorRT engine file.
  58. workspace (int, optional): Workspace size in GB for TensorRT. Defaults to None.
  59. half (bool, optional): Enable FP16 precision. Defaults to False.
  60. int8 (bool, optional): Enable INT8 precision. Defaults to False.
  61. dynamic (bool, optional): Enable dynamic input shapes. Defaults to False.
  62. shape (tuple, optional): Input shape (batch, channels, height, width). Defaults to (1, 3, 640, 640).
  63. dla (int, optional): DLA core to use (Jetson devices only). Defaults to None.
  64. dataset (ultralytics.data.build.InfiniteDataLoader, optional): Dataset for INT8 calibration. Defaults to None.
  65. metadata (dict, optional): Metadata to include in the engine file. Defaults to None.
  66. verbose (bool, optional): Enable verbose logging. Defaults to False.
  67. prefix (str, optional): Prefix for log messages. Defaults to "".
  68. Raises:
  69. ValueError: If DLA is enabled on non-Jetson devices or required precision is not set.
  70. RuntimeError: If the ONNX file cannot be parsed.
  71. Notes:
  72. - TensorRT version compatibility is handled for workspace size and engine building.
  73. - INT8 calibration requires a dataset and generates a calibration cache.
  74. - Metadata is serialized and written to the engine file if provided.
  75. """
  76. import tensorrt as trt # noqa
  77. engine_file = engine_file or Path(onnx_file).with_suffix(".engine")
  78. logger = trt.Logger(trt.Logger.INFO)
  79. if verbose:
  80. logger.min_severity = trt.Logger.Severity.VERBOSE
  81. # Engine builder
  82. builder = trt.Builder(logger)
  83. config = builder.create_builder_config()
  84. workspace = int((workspace or 0) * (1 << 30))
  85. is_trt10 = int(trt.__version__.split(".")[0]) >= 10 # is TensorRT >= 10
  86. if is_trt10 and workspace > 0:
  87. config.set_memory_pool_limit(trt.MemoryPoolType.WORKSPACE, workspace)
  88. elif workspace > 0: # TensorRT versions 7, 8
  89. config.max_workspace_size = workspace
  90. flag = 1 << int(trt.NetworkDefinitionCreationFlag.EXPLICIT_BATCH)
  91. network = builder.create_network(flag)
  92. half = builder.platform_has_fast_fp16 and half
  93. int8 = builder.platform_has_fast_int8 and int8
  94. # Optionally switch to DLA if enabled
  95. if dla is not None:
  96. if not IS_JETSON:
  97. raise ValueError("DLA is only available on NVIDIA Jetson devices")
  98. LOGGER.info(f"{prefix} enabling DLA on core {dla}...")
  99. if not half and not int8:
  100. raise ValueError(
  101. "DLA requires either 'half=True' (FP16) or 'int8=True' (INT8) to be enabled. Please enable one of them and try again."
  102. )
  103. config.default_device_type = trt.DeviceType.DLA
  104. config.DLA_core = int(dla)
  105. config.set_flag(trt.BuilderFlag.GPU_FALLBACK)
  106. # Read ONNX file
  107. parser = trt.OnnxParser(network, logger)
  108. if not parser.parse_from_file(onnx_file):
  109. raise RuntimeError(f"failed to load ONNX file: {onnx_file}")
  110. # Network inputs
  111. inputs = [network.get_input(i) for i in range(network.num_inputs)]
  112. outputs = [network.get_output(i) for i in range(network.num_outputs)]
  113. for inp in inputs:
  114. LOGGER.info(f'{prefix} input "{inp.name}" with shape{inp.shape} {inp.dtype}')
  115. for out in outputs:
  116. LOGGER.info(f'{prefix} output "{out.name}" with shape{out.shape} {out.dtype}')
  117. if dynamic:
  118. if shape[0] <= 1:
  119. LOGGER.warning(f"{prefix} 'dynamic=True' model requires max batch size, i.e. 'batch=16'")
  120. profile = builder.create_optimization_profile()
  121. min_shape = (1, shape[1], 32, 32) # minimum input shape
  122. max_shape = (*shape[:2], *(int(max(1, workspace or 1) * d) for d in shape[2:])) # max input shape
  123. for inp in inputs:
  124. profile.set_shape(inp.name, min=min_shape, opt=shape, max=max_shape)
  125. config.add_optimization_profile(profile)
  126. LOGGER.info(f"{prefix} building {'INT8' if int8 else 'FP' + ('16' if half else '32')} engine as {engine_file}")
  127. if int8:
  128. config.set_flag(trt.BuilderFlag.INT8)
  129. config.set_calibration_profile(profile)
  130. config.profiling_verbosity = trt.ProfilingVerbosity.DETAILED
  131. class EngineCalibrator(trt.IInt8Calibrator):
  132. """
  133. Custom INT8 calibrator for TensorRT.
  134. Args:
  135. dataset (object): Dataset for calibration.
  136. batch (int): Batch size for calibration.
  137. cache (str, optional): Path to save the calibration cache. Defaults to "".
  138. """
  139. def __init__(
  140. self,
  141. dataset, # ultralytics.data.build.InfiniteDataLoader
  142. cache: str = "",
  143. ) -> None:
  144. trt.IInt8Calibrator.__init__(self)
  145. self.dataset = dataset
  146. self.data_iter = iter(dataset)
  147. self.algo = trt.CalibrationAlgoType.ENTROPY_CALIBRATION_2
  148. self.batch = dataset.batch_size
  149. self.cache = Path(cache)
  150. def get_algorithm(self) -> trt.CalibrationAlgoType:
  151. """Get the calibration algorithm to use."""
  152. return self.algo
  153. def get_batch_size(self) -> int:
  154. """Get the batch size to use for calibration."""
  155. return self.batch or 1
  156. def get_batch(self, names) -> list:
  157. """Get the next batch to use for calibration, as a list of device memory pointers."""
  158. try:
  159. im0s = next(self.data_iter)["img"] / 255.0
  160. im0s = im0s.to("cuda") if im0s.device.type == "cpu" else im0s
  161. return [int(im0s.data_ptr())]
  162. except StopIteration:
  163. # Return [] or None, signal to TensorRT there is no calibration data remaining
  164. return None
  165. def read_calibration_cache(self) -> bytes:
  166. """Use existing cache instead of calibrating again, otherwise, implicitly return None."""
  167. if self.cache.exists() and self.cache.suffix == ".cache":
  168. return self.cache.read_bytes()
  169. def write_calibration_cache(self, cache) -> None:
  170. """Write calibration cache to disk."""
  171. _ = self.cache.write_bytes(cache)
  172. # Load dataset w/ builder (for batching) and calibrate
  173. config.int8_calibrator = EngineCalibrator(
  174. dataset=dataset,
  175. cache=str(Path(onnx_file).with_suffix(".cache")),
  176. )
  177. elif half:
  178. config.set_flag(trt.BuilderFlag.FP16)
  179. # Write file
  180. build = builder.build_serialized_network if is_trt10 else builder.build_engine
  181. with build(network, config) as engine, open(engine_file, "wb") as t:
  182. # Metadata
  183. if metadata is not None:
  184. meta = json.dumps(metadata)
  185. t.write(len(meta).to_bytes(4, byteorder="little", signed=True))
  186. t.write(meta.encode())
  187. # Model
  188. t.write(engine if is_trt10 else engine.serialize())
Discard
Tip!

Press p or to see the previous file or, n or to see the next file