firstlight 0.1.0.dev0__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.
firstlight/trt.py ADDED
@@ -0,0 +1,668 @@
1
+ """Runs on an NVIDIA GPU with TensorRT: the device run (2 iterations, keep the states) and the
2
+ energy of one iteration from the GPU's energy counter."""
3
+
4
+ from __future__ import annotations
5
+
6
+ import hashlib
7
+ import json
8
+ import logging
9
+ import time
10
+ from dataclasses import dataclass
11
+ from pathlib import Path
12
+ from typing import Any
13
+
14
+ import numpy as np
15
+
16
+ from .aihub import ITERATIONS, _build_digest, _first_feed, _save
17
+ from .host import _answer
18
+ from .model import Spec
19
+
20
+ logger = logging.getLogger(__name__)
21
+
22
+ SCHEMA = 1
23
+ PRECISIONS = ("fp32", "fp16", "int8")
24
+ INSTALL = "Install them with: pip install 'firstlight[tensorrt]'"
25
+ # The energy run, as in the paper's L40S windows: 10 s of the same work before the first repeat
26
+ # (clocks up, lazy CUDA set-up done), then each repeat reads the energy counter before and after.
27
+ WARMUP_S = 10.0
28
+ REPEATS = 3
29
+
30
+
31
+ @dataclass(frozen=True)
32
+ class GpuRun:
33
+ """The result of a device run on TensorRT.
34
+
35
+ Parameters
36
+ ----------
37
+ states : Path
38
+ The file that ``firstlight check --states`` reads.
39
+ record : Path
40
+ The file of the engine record: the TensorRT version, the GPU, and the build digest.
41
+ engine : Path
42
+ The engine file that ran.
43
+ ms_per_iteration : tuple[float, ...]
44
+ The median time of one iteration on the GPU for each iteration, in milliseconds, without
45
+ the copies to and from the host.
46
+ toolchain_version : str
47
+ The TensorRT version.
48
+ gpu : str
49
+ The name of the GPU.
50
+ """
51
+
52
+ states: Path
53
+ record: Path
54
+ engine: Path
55
+ ms_per_iteration: tuple[float, ...]
56
+ toolchain_version: str
57
+ gpu: str
58
+
59
+
60
+ @dataclass(frozen=True)
61
+ class EnergyRun:
62
+ """The energy of one iteration on the GPU, from NVML's total-energy counter.
63
+
64
+ Parameters
65
+ ----------
66
+ engine : Path
67
+ The engine file that ran.
68
+ iterations : int
69
+ The iterations in each repeat.
70
+ mj_per_iteration : tuple[float, ...]
71
+ The energy of the GPU over each repeat divided by its iterations, in mJ. It is the whole
72
+ card's energy, with no idle power subtracted.
73
+ ms_per_iteration : tuple[float, ...]
74
+ The time of each repeat divided by its iterations, in ms.
75
+ watts : tuple[float, ...]
76
+ The mean power of the GPU over each repeat, in W.
77
+ toolchain_version : str
78
+ The TensorRT version.
79
+ gpu : str
80
+ The name of the GPU.
81
+ """
82
+
83
+ engine: Path
84
+ iterations: int
85
+ mj_per_iteration: tuple[float, ...]
86
+ ms_per_iteration: tuple[float, ...]
87
+ watts: tuple[float, ...]
88
+ toolchain_version: str
89
+ gpu: str
90
+
91
+
92
+ def record_path(states: str | Path) -> Path:
93
+ """Return the file of the engine record for the states file ``states``: <name>.engine.json."""
94
+ states = Path(states)
95
+ return states.with_name(f"{states.stem}.engine.json")
96
+
97
+
98
+ def gpu_run(
99
+ spec: Spec,
100
+ build: str | Path,
101
+ device: str,
102
+ inputs: dict[str, np.ndarray],
103
+ out: str | Path,
104
+ precision: str | None = None,
105
+ engine: str | Path | None = None,
106
+ ) -> GpuRun:
107
+ """Build ``build`` with TensorRT on this GPU, run 2 iterations, and write the states.
108
+
109
+ The engine file goes to ``<out stem>.engine`` and its record to ``<out stem>.engine.json``.
110
+ A second call with the same arguments uses the engine file and builds nothing. The host
111
+ gives the hidden state that the GPU returned after iteration 1 to iteration 2.
112
+
113
+ Parameters
114
+ ----------
115
+ spec : Spec
116
+ The looped model. Its start gives the hidden state before iteration 1.
117
+ build : str | Path
118
+ The ONNX graph of one iteration. It takes and gives the names of ``spec``.
119
+ device : str
120
+ A part of the GPU name, for example "L40S". The run stops on another GPU.
121
+ inputs : dict[str, np.ndarray]
122
+ One array for each task input, with the N inputs on axis 0.
123
+ out : str | Path
124
+ The .npz file to write, as ``firstlight.aihub.device_run`` writes it.
125
+ precision : str | None
126
+ A member of ``PRECISIONS``: ``fp32``, ``fp16``, or ``int8``. ``int8`` sets the INT8 and
127
+ FP16 flags and needs a graph with QuantizeLinear nodes (explicit INT8). Give it or
128
+ ``engine``.
129
+ engine : str | Path | None
130
+ An engine file to run in place of a build. Then ``build`` gives only the names.
131
+
132
+ Returns
133
+ -------
134
+ GpuRun
135
+ The paths of the files, the time per iteration, the TensorRT version and the GPU.
136
+
137
+ Raises
138
+ ------
139
+ ImportError
140
+ If ``tensorrt`` or ``cuda-python`` is not installed.
141
+ ValueError
142
+ If the precision is not known or does not fit the graph, the GPU is not ``device``, the
143
+ record holds another build, or the engine takes inputs that the feed does not give.
144
+ RuntimeError
145
+ If TensorRT does not build or load the engine, or a CUDA call fails.
146
+ """
147
+ trt, cudart = _modules()
148
+ build, out = Path(build), Path(out)
149
+ graph = _graph(build, precision, engine)
150
+ spec, feed, n = _first_feed(spec, build, inputs)
151
+ gpu = _gpu_name(cudart)
152
+ if device.lower() not in gpu.lower():
153
+ raise ValueError(f"The GPU is {gpu!r}, not the device {device!r}.")
154
+ trt_logger = trt.Logger(trt.Logger.WARNING)
155
+ path = record_path(out)
156
+ if engine is not None:
157
+ engine = Path(engine)
158
+ else:
159
+ engine = out.with_suffix(".engine")
160
+ _engine_file(trt, trt_logger, build, graph, precision, gpu, engine, path)
161
+ loaded = _load(trt, trt_logger, engine, gpu)
162
+ kept, answers, ms = _iterate(trt, cudart, loaded, spec, feed, n, build)
163
+ arrays = {"iteration_1": kept[0], "iteration_2": kept[1]}
164
+ if answers:
165
+ arrays["predictions"] = np.stack(answers)
166
+ arrays["toolchain"] = np.array("tensorrt")
167
+ arrays["toolchain_version"] = np.array(str(trt.__version__))
168
+ out.parent.mkdir(parents=True, exist_ok=True)
169
+ np.savez(out, **arrays)
170
+ if precision is None:
171
+ _save(
172
+ path,
173
+ {
174
+ "schema": SCHEMA,
175
+ "toolchain": "tensorrt",
176
+ "toolchain_version": str(trt.__version__),
177
+ "gpu": gpu,
178
+ "engine": str(engine),
179
+ "engine_sha256": _sha256(engine),
180
+ },
181
+ )
182
+ return GpuRun(
183
+ states=out,
184
+ record=path,
185
+ engine=engine,
186
+ ms_per_iteration=tuple(ms),
187
+ toolchain_version=str(trt.__version__),
188
+ gpu=gpu,
189
+ )
190
+
191
+
192
+ def _graph(build: Path, precision: str | None, engine: str | Path | None) -> Any:
193
+ """Return the ONNX graph of ``build`` after checking ``precision`` and ``engine``.
194
+
195
+ Raises
196
+ ------
197
+ ValueError
198
+ If both or neither of ``precision`` and ``engine`` are given, or the precision is not
199
+ known or does not fit the graph.
200
+ """
201
+ import onnx
202
+
203
+ if (precision is None) == (engine is None):
204
+ raise ValueError("Give --precision or --engine for the toolchain tensorrt, not both.")
205
+ if precision is not None and precision not in PRECISIONS:
206
+ raise ValueError(f"The precision {precision!r} is not one of {list(PRECISIONS)}.")
207
+ graph = onnx.load(build, load_external_data=False).graph
208
+ if precision == "int8" and not any(node.op_type == "QuantizeLinear" for node in graph.node):
209
+ raise ValueError(
210
+ f"The graph {build} has no QuantizeLinear node. The precision int8 needs an explicit "
211
+ "INT8 graph; FirstLight does not calibrate an implicit INT8 build."
212
+ )
213
+ return graph
214
+
215
+
216
+ def _engine_file(
217
+ trt: Any,
218
+ trt_logger: Any,
219
+ build: Path,
220
+ graph: Any,
221
+ precision: str,
222
+ gpu: str,
223
+ engine: Path,
224
+ record: Path,
225
+ ) -> None:
226
+ """Build ``build`` at ``precision`` into ``engine`` and write ``record``, or reuse both."""
227
+ key = {
228
+ "toolchain": "tensorrt",
229
+ "toolchain_version": str(trt.__version__),
230
+ "gpu": gpu,
231
+ "build_sha256": _build_digest(build, graph),
232
+ "precision": precision,
233
+ }
234
+ if _reuse(record, engine, key):
235
+ return
236
+ start = time.perf_counter()
237
+ engine.parent.mkdir(parents=True, exist_ok=True)
238
+ engine.write_bytes(_build(trt, trt_logger, build, precision))
239
+ seconds = round(time.perf_counter() - start, 1)
240
+ logger.info("built %s at %s in %s s", engine, precision, seconds)
241
+ _save(record, {"schema": SCHEMA, **key, "engine_sha256": _sha256(engine)})
242
+
243
+
244
+ def _load(trt: Any, trt_logger: Any, engine: Path, gpu: str) -> Any:
245
+ """Return the engine of the file ``engine``.
246
+
247
+ Raises
248
+ ------
249
+ RuntimeError
250
+ If TensorRT cannot load the file on this GPU.
251
+ """
252
+ loaded = trt.Runtime(trt_logger).deserialize_cuda_engine(engine.read_bytes())
253
+ if loaded is None:
254
+ raise RuntimeError(
255
+ f"TensorRT {trt.__version__} cannot load the engine file {engine} on {gpu}. An engine "
256
+ "file runs only with the TensorRT version and the GPU type that built it."
257
+ )
258
+ return loaded
259
+
260
+
261
+ def _modules() -> tuple[Any, Any]:
262
+ """Return the ``tensorrt`` module and the CUDA runtime of ``cuda-python``.
263
+
264
+ Raises
265
+ ------
266
+ ImportError
267
+ If one of them is not installed.
268
+ """
269
+ try:
270
+ import tensorrt as trt
271
+ except ImportError as error:
272
+ raise ImportError(f"The TensorRT run needs tensorrt and cuda-python. {INSTALL}") from error
273
+ try:
274
+ from cuda.bindings import runtime as cudart
275
+ except ImportError:
276
+ try:
277
+ from cuda import cudart # cuda-python before 12.6
278
+ except ImportError as error:
279
+ raise ImportError(f"The TensorRT run needs cuda-python. {INSTALL}") from error
280
+ return trt, cudart
281
+
282
+
283
+ def _call(cudart: Any, result: tuple[Any, ...]) -> Any:
284
+ """Return the value of a CUDA call of cuda-python, which gives (error, value...).
285
+
286
+ Raises
287
+ ------
288
+ RuntimeError
289
+ If the error is not ``cudaSuccess``.
290
+ """
291
+ error, *values = result
292
+ if error != cudart.cudaError_t.cudaSuccess:
293
+ raise RuntimeError(f"A CUDA call failed: {error}.")
294
+ return values[0] if values else None
295
+
296
+
297
+ def _gpu_name(cudart: Any) -> str:
298
+ """Return the name of the current GPU, for example "NVIDIA L40S"."""
299
+ props = _call(cudart, cudart.cudaGetDeviceProperties(_call(cudart, cudart.cudaGetDevice())))
300
+ name = props.name
301
+ return (name.decode() if isinstance(name, bytes) else str(name)).rstrip("\x00")
302
+
303
+
304
+ def _sha256(path: Path) -> str:
305
+ """Return the sha256 of a file."""
306
+ return hashlib.sha256(path.read_bytes()).hexdigest()
307
+
308
+
309
+ def _reuse(path: Path, engine: Path, key: dict[str, Any]) -> bool:
310
+ """Return True when the engine file and its record exist and the record holds ``key``.
311
+
312
+ Raises
313
+ ------
314
+ ValueError
315
+ If the record holds another schema, another build, TensorRT version, GPU or precision,
316
+ or the engine file changed after the build.
317
+ """
318
+ if not (path.exists() and engine.exists()):
319
+ return False
320
+ record = json.loads(path.read_text())
321
+ if record.get("schema") != SCHEMA:
322
+ raise ValueError(
323
+ f"{path} has the schema {record.get('schema')!r}, not {SCHEMA}. Remove the file."
324
+ )
325
+ for k, v in key.items():
326
+ if record.get(k) != v:
327
+ raise ValueError(
328
+ f"{path} holds the engine of another build: its {k} is {record.get(k)!r}, this "
329
+ f"run has {v!r}. Give another output file, or remove {path} and {engine}."
330
+ )
331
+ if record.get("engine_sha256") != _sha256(engine):
332
+ raise ValueError(f"{engine} changed after its build. Remove {engine} and {path}.")
333
+ logger.info("use the engine file %s", engine)
334
+ return True
335
+
336
+
337
+ def _build(trt: Any, trt_logger: Any, build: Path, precision: str) -> bytes:
338
+ """Return the engine of ``build`` at ``precision``, with TF32 off as in the paper's builds.
339
+
340
+ Raises
341
+ ------
342
+ RuntimeError
343
+ If TensorRT does not parse the graph or does not build the engine.
344
+ """
345
+ builder = trt.Builder(trt_logger)
346
+ network = builder.create_network(0)
347
+ parser = trt.OnnxParser(network, trt_logger)
348
+ if not parser.parse_from_file(str(build)):
349
+ errors = [str(parser.get_error(i)) for i in range(parser.num_errors)]
350
+ raise RuntimeError(f"TensorRT cannot parse {build}: {errors}")
351
+ config = builder.create_builder_config()
352
+ config.clear_flag(trt.BuilderFlag.TF32)
353
+ if precision in ("fp16", "int8"):
354
+ config.set_flag(trt.BuilderFlag.FP16)
355
+ if precision == "int8":
356
+ config.set_flag(trt.BuilderFlag.INT8)
357
+ serialized = builder.build_serialized_network(network, config)
358
+ if serialized is None:
359
+ raise RuntimeError(f"TensorRT built no engine of {build} at {precision}; see its log.")
360
+ return bytes(serialized)
361
+
362
+
363
+ def _iterate(
364
+ trt: Any,
365
+ cudart: Any,
366
+ engine: Any,
367
+ spec: Spec,
368
+ feed: dict[str, list[np.ndarray]],
369
+ n: int,
370
+ build: Path,
371
+ ) -> tuple[list[np.ndarray], list[np.ndarray], list[float]]:
372
+ """Run 2 iterations on each input and return the check states, the answers and the times.
373
+
374
+ Raises
375
+ ------
376
+ ValueError
377
+ If the engine takes an input that the feed does not give, or with another dtype or shape.
378
+ RuntimeError
379
+ If an execution of the engine fails.
380
+ """
381
+ context = engine.create_execution_context()
382
+ names = [engine.get_tensor_name(i) for i in range(engine.num_io_tensors)]
383
+ ins = [k for k in names if engine.get_tensor_mode(k) == trt.TensorIOMode.INPUT]
384
+ outs = [k for k in names if k not in ins]
385
+ if missing := set(ins) - set(feed):
386
+ raise ValueError(
387
+ f"The engine of {build} takes the inputs {sorted(missing)}, which are not states or "
388
+ f"task inputs of the spec: {sorted(feed)}."
389
+ )
390
+ dtypes = {k: np.dtype(trt.nptype(engine.get_tensor_dtype(k))) for k in names}
391
+ shapes = {k: tuple(context.get_tensor_shape(k)) for k in names}
392
+ h2d = cudart.cudaMemcpyKind.cudaMemcpyHostToDevice
393
+ d2h = cudart.cudaMemcpyKind.cudaMemcpyDeviceToHost
394
+ stream = _call(cudart, cudart.cudaStreamCreate())
395
+ pointers: dict[str, int] = {}
396
+ kept, answers, ms = [], [], []
397
+ try:
398
+ for k in names:
399
+ size = int(np.prod(shapes[k])) * dtypes[k].itemsize
400
+ pointers[k] = int(_call(cudart, cudart.cudaMalloc(size)))
401
+ context.set_tensor_address(k, pointers[k])
402
+ for it in range(1, ITERATIONS + 1):
403
+ given: dict[str, list[np.ndarray]] = {k: [] for k in outs}
404
+ times = []
405
+ for i in range(n):
406
+ for k in ins:
407
+ a = np.ascontiguousarray(feed[k][i])
408
+ if a.dtype != dtypes[k] or a.shape != shapes[k]:
409
+ raise ValueError(
410
+ f"The engine of {build} takes {k!r} as {dtypes[k]} {shapes[k]}, but "
411
+ f"the feed gives {a.dtype} {a.shape} in iteration {it}."
412
+ )
413
+ _call(
414
+ cudart,
415
+ cudart.cudaMemcpyAsync(pointers[k], a.ctypes.data, a.nbytes, h2d, stream),
416
+ )
417
+ _call(cudart, cudart.cudaStreamSynchronize(stream))
418
+ start = time.perf_counter()
419
+ if not context.execute_async_v3(int(stream)):
420
+ raise RuntimeError(f"TensorRT failed to run the engine of {build}.")
421
+ _call(cudart, cudart.cudaStreamSynchronize(stream))
422
+ times.append((time.perf_counter() - start) * 1000)
423
+ for k in outs:
424
+ x = np.empty(shapes[k], dtypes[k])
425
+ _call(
426
+ cudart,
427
+ cudart.cudaMemcpyAsync(x.ctypes.data, pointers[k], x.nbytes, d2h, stream),
428
+ )
429
+ given[k].append(x)
430
+ _call(cudart, cudart.cudaStreamSynchronize(stream))
431
+ state = {s: [x.astype(np.float32) for x in given[f"{s}_out"]] for s in spec.states}
432
+ kept.append(np.stack([x[0] for x in state[spec.check_state]]))
433
+ if "logits" in given:
434
+ answers.append(np.stack([_answer(x, spec.classes_axis) for x in given["logits"]]))
435
+ ms.append(float(np.median(times)))
436
+ feed.update(state)
437
+ finally:
438
+ for p in pointers.values():
439
+ cudart.cudaFree(p)
440
+ cudart.cudaStreamDestroy(stream)
441
+ return kept, answers, ms
442
+
443
+
444
+ def gpu_energy(
445
+ spec: Spec,
446
+ build: str | Path,
447
+ inputs: dict[str, np.ndarray],
448
+ precision: str | None = None,
449
+ engine: str | Path | None = None,
450
+ iterations: int = 10000,
451
+ ) -> EnergyRun:
452
+ """Run ``iterations`` iterations of ``build`` at batch size 1 on this GPU, 3 times, and
453
+ give the energy of one iteration.
454
+
455
+ The hidden state stays on the GPU: each iteration takes the state that the iteration before
456
+ it gave. After ``spec.limit`` iterations (16 when the spec has no limit) the run starts the
457
+ next input from its start state, as a run of the model to its limit does. The run waits for
458
+ the GPU only there. 10 s of the same work come before the first repeat. The engine file goes
459
+ to ``<build stem>_<precision>.engine`` in the current folder, with its record beside it.
460
+
461
+ Parameters
462
+ ----------
463
+ spec : Spec
464
+ The looped model.
465
+ build : str | Path
466
+ The ONNX graph of one iteration.
467
+ inputs : dict[str, np.ndarray]
468
+ One array for each task input, with the N inputs on axis 0. The run goes through them in
469
+ turn.
470
+ precision : str | None
471
+ ``fp32``, ``fp16`` or ``int8``, as for ``gpu_run``. Give it or ``engine``.
472
+ engine : str | Path | None
473
+ An engine file to run in place of a build.
474
+ iterations : int
475
+ The iterations in each repeat, at least 1.
476
+
477
+ Returns
478
+ -------
479
+ EnergyRun
480
+ The energy, time and mean power of one iteration in each repeat.
481
+
482
+ Raises
483
+ ------
484
+ ImportError
485
+ If ``tensorrt``, ``cuda-python`` or ``nvidia-ml-py`` is not installed.
486
+ ValueError
487
+ As for ``gpu_run``, or if ``iterations`` is below 1.
488
+ RuntimeError
489
+ If TensorRT does not build or load the engine, a CUDA call fails, or NVML does not find
490
+ the GPU or has no energy counter for it.
491
+ """
492
+ if iterations < 1:
493
+ raise ValueError(f"The energy run needs at least 1 iteration, not {iterations}.")
494
+ trt, cudart = _modules()
495
+ nvml = _nvml()
496
+ build = Path(build)
497
+ graph = _graph(build, precision, engine)
498
+ spec, feed, n = _first_feed(spec, build, inputs)
499
+ gpu = _gpu_name(cudart)
500
+ trt_logger = trt.Logger(trt.Logger.WARNING)
501
+ if engine is not None:
502
+ engine = Path(engine)
503
+ else:
504
+ engine = Path(f"{build.stem}_{precision}.engine")
505
+ record = engine.with_name(f"{engine.name}.json")
506
+ _engine_file(trt, trt_logger, build, graph, precision, gpu, engine, record)
507
+ loaded = _load(trt, trt_logger, engine, gpu)
508
+ handle = _nvml_handle(nvml, cudart)
509
+ mj, ms, watts = _energy_loop(
510
+ trt, cudart, nvml, handle, loaded, spec, feed, n, build, iterations
511
+ )
512
+ return EnergyRun(
513
+ engine=engine,
514
+ iterations=iterations,
515
+ mj_per_iteration=tuple(mj),
516
+ ms_per_iteration=tuple(ms),
517
+ watts=tuple(watts),
518
+ toolchain_version=str(trt.__version__),
519
+ gpu=gpu,
520
+ )
521
+
522
+
523
+ def _nvml() -> Any:
524
+ """Return the ``pynvml`` module of ``nvidia-ml-py``, initialized.
525
+
526
+ Raises
527
+ ------
528
+ ImportError
529
+ If it is not installed.
530
+ """
531
+ try:
532
+ import pynvml
533
+ except ImportError as error:
534
+ raise ImportError(f"The energy run needs nvidia-ml-py. {INSTALL}") from error
535
+ pynvml.nvmlInit()
536
+ return pynvml
537
+
538
+
539
+ def _nvml_handle(nvml: Any, cudart: Any) -> Any:
540
+ """Return the NVML handle of the current CUDA device, found by its UUID.
541
+
542
+ NVML numbers the GPUs of the machine, and CUDA only the visible ones, so the indices can
543
+ differ.
544
+
545
+ Raises
546
+ ------
547
+ RuntimeError
548
+ If no NVML device has the UUID of the CUDA device.
549
+ """
550
+ props = _call(cudart, cudart.cudaGetDeviceProperties(_call(cudart, cudart.cudaGetDevice())))
551
+ raw = props.uuid.bytes
552
+ h = (raw.encode("latin-1") if isinstance(raw, str) else bytes(raw)).hex()
553
+ uuid = f"GPU-{h[:8]}-{h[8:12]}-{h[12:16]}-{h[16:20]}-{h[20:32]}"
554
+ for i in range(nvml.nvmlDeviceGetCount()):
555
+ handle = nvml.nvmlDeviceGetHandleByIndex(i)
556
+ found = nvml.nvmlDeviceGetUUID(handle)
557
+ if (found.decode() if isinstance(found, bytes) else found) == uuid:
558
+ return handle
559
+ raise RuntimeError(f"NVML has no GPU with the UUID {uuid} of the CUDA device.")
560
+
561
+
562
+ def _energy_loop(
563
+ trt: Any,
564
+ cudart: Any,
565
+ nvml: Any,
566
+ handle: Any,
567
+ engine: Any,
568
+ spec: Spec,
569
+ feed: dict[str, list[np.ndarray]],
570
+ n: int,
571
+ build: Path,
572
+ iterations: int,
573
+ ) -> tuple[list[float], list[float], list[float]]:
574
+ """Run the repeats and return the mJ and ms per iteration and the mean W of each.
575
+
576
+ The inputs and start states of all N inputs go to the GPU once. Each state has two more
577
+ buffers, which the iterations write in turn; no copy is made during a repeat.
578
+
579
+ Raises
580
+ ------
581
+ ValueError
582
+ If the engine takes an input that the feed does not give, or with another dtype or shape.
583
+ RuntimeError
584
+ If an execution of the engine fails.
585
+ """
586
+ context = engine.create_execution_context()
587
+ names = [engine.get_tensor_name(i) for i in range(engine.num_io_tensors)]
588
+ ins = [k for k in names if engine.get_tensor_mode(k) == trt.TensorIOMode.INPUT]
589
+ if missing := set(ins) - set(feed):
590
+ raise ValueError(
591
+ f"The engine of {build} takes the inputs {sorted(missing)}, which are not states or "
592
+ f"task inputs of the spec: {sorted(feed)}."
593
+ )
594
+ for k in ins:
595
+ if -1 in tuple(engine.get_tensor_shape(k)): # an engine built with a batch range
596
+ context.set_input_shape(k, feed[k][0].shape)
597
+ dtypes = {k: np.dtype(trt.nptype(engine.get_tensor_dtype(k))) for k in names}
598
+ shapes = {k: tuple(context.get_tensor_shape(k)) for k in names}
599
+ for k in ins:
600
+ a = feed[k][0]
601
+ if a.dtype != dtypes[k] or a.shape != shapes[k]:
602
+ raise ValueError(
603
+ f"The engine of {build} takes {k!r} as {dtypes[k]} {shapes[k]}, but the feed "
604
+ f"gives {a.dtype} {a.shape}."
605
+ )
606
+ h2d = cudart.cudaMemcpyKind.cudaMemcpyHostToDevice
607
+ stream = _call(cudart, cudart.cudaStreamCreate())
608
+ pointers: list[int] = []
609
+
610
+ def alloc(nbytes: int) -> int:
611
+ pointers.append(int(_call(cudart, cudart.cudaMalloc(nbytes))))
612
+ return pointers[-1]
613
+
614
+ limit = spec.limit or 16
615
+ try:
616
+ given: dict[str, list[int]] = {} # the device copy of each input's array
617
+ for k in ins:
618
+ block = np.ascontiguousarray(np.stack(feed[k][:n]))
619
+ base, size = alloc(block.nbytes), block.nbytes // n
620
+ _call(
621
+ cudart, cudart.cudaMemcpyAsync(base, block.ctypes.data, block.nbytes, h2d, stream)
622
+ )
623
+ given[k] = [base + i * size for i in range(n)]
624
+ turn = {} # the two buffers of each state
625
+ for s in spec.states:
626
+ size = int(np.prod(shapes[s])) * dtypes[s].itemsize
627
+ turn[s] = [alloc(size), alloc(size)]
628
+ for k in names:
629
+ if k not in ins and k not in {f"{s}_out" for s in turn}:
630
+ context.set_tensor_address(k, alloc(int(np.prod(shapes[k])) * dtypes[k].itemsize))
631
+ _call(cudart, cudart.cudaStreamSynchronize(stream))
632
+ done = [0] # iterations run so far, over all repeats
633
+
634
+ def run(count: int) -> None:
635
+ for _ in range(count):
636
+ i, it = divmod(done[0], limit)
637
+ i %= n
638
+ if it == 0:
639
+ _call(cudart, cudart.cudaStreamSynchronize(stream))
640
+ for k in ins:
641
+ if k not in turn:
642
+ context.set_tensor_address(k, given[k][i])
643
+ for s, (a, b) in turn.items():
644
+ source = given[s][i] if it == 0 else (a, b)[it % 2]
645
+ context.set_tensor_address(s, source)
646
+ context.set_tensor_address(f"{s}_out", (a, b)[(it + 1) % 2])
647
+ if not context.execute_async_v3(int(stream)):
648
+ raise RuntimeError(f"TensorRT failed to run the engine of {build}.")
649
+ done[0] += 1
650
+ _call(cudart, cudart.cudaStreamSynchronize(stream))
651
+
652
+ start = time.perf_counter()
653
+ run(limit) # at least one input of warm-up
654
+ while time.perf_counter() - start < WARMUP_S:
655
+ run(limit)
656
+ mj, ms, watts = [], [], []
657
+ for _ in range(REPEATS):
658
+ e0, t0 = nvml.nvmlDeviceGetTotalEnergyConsumption(handle), time.perf_counter()
659
+ run(iterations)
660
+ e1, t1 = nvml.nvmlDeviceGetTotalEnergyConsumption(handle), time.perf_counter()
661
+ mj.append((e1 - e0) / iterations)
662
+ ms.append((t1 - t0) * 1000 / iterations)
663
+ watts.append((e1 - e0) / 1000 / (t1 - t0))
664
+ finally:
665
+ for p in pointers:
666
+ cudart.cudaFree(p)
667
+ cudart.cudaStreamDestroy(stream)
668
+ return mj, ms, watts