forked from Lightning-AI/lightning-thunder
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path__init__.py
More file actions
3721 lines (3052 loc) · 129 KB
/
Copy path__init__.py
File metadata and controls
3721 lines (3052 loc) · 129 KB
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
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import dataclasses
import sys
import tempfile
import textwrap
import time
from collections import UserDict
from collections.abc import Callable
from collections.abc import Sequence
from dataclasses import dataclass
from functools import partial
from numbers import Number
from typing import Any
from contextlib import contextmanager
import torch
import torch.multiprocessing as mp
import torch.nn as nn
from lightning_utilities.core.imports import package_available
import thunder
import thunder.dynamo
import thunder.core.devices as Devices
import thunder.core.dtypes as dtypes
import thunder.executors as executors
import thunder.torch as ltorch
from thunder.core.transforms import grad, clear_grads, populate_grads
from thunder.executors.apexex import apex_ex, apex_entropy_available
from thunder.executors.cudnn_layernormex import cudnn_layernorm_ex
from thunder.executors.cudnnex import cudnn_ex, cudnn_available
from thunder.executors.transformer_engineex import transformer_engine_ex, TransformerEngineTransform
from thunder.executors.sdpaex import sdpa_ex
from thunder.executors.torch_compile import torch_compile_cat_ex, torch_compile_ex
from thunder.transforms.cudagraph import CUDAGraphTransform
from thunder.tests import nanogpt_model, hf_bart_self_attn
from thunder.tests.make_tensor import make_tensor, make_tensor_like
MAX_ALLOCATED_MEMORY_KEYWORD = "max_allocated_memory_MB"
# List of all benchmarks
benchmarks: list = []
# Prints the benchmarks in alphabetical order (either by classname or the benchmark's "name" attribute)
def list_benchmarks(use_classname: bool = True) -> None:
print("Available benchmarks:")
if use_classname:
def name_fn(x):
return x[0]
else:
def name_fn(x):
return x[1].name
for x in sorted(benchmarks, key=name_fn):
name = name_fn(x)
cls_name, b = x
print(f"\t{name}. {b.description}")
@dataclasses.dataclass
class BenchmarkArg:
"""
Describes a benchmark argument.
"""
name: str
description: str
# TODO Update the metaclass to review the class and point out missing properties/mistakes (like not defining a name)
# Simple metaclass that automatically adds defined benchmarks to the list of benchmarks above
class UserFacingBenchmarkMeta(type):
def __new__(metacls, clsname, bases, namespace):
return super().__new__(metacls, clsname, bases, namespace)
def __init__(cls: type, name: str, bases, namespace: dict) -> None:
benchmarks.append((name, cls))
return None
# Base class for benchmarks
class Benchmark:
"""
Encapsulates a benchmark.
To add a benchmark:
1) Create a new class for the benchmark that is a subclass of this class.
2) If the benchmark should be user-facing (for example, it is not a subclass of Benchmark
designed to be inherited by other benchmarks), then set the class's metaclass to
UserFacingBenchmarkMeta:
class MyBenchmark(Benchmark, metaclass=UserFacingBenchmarkMeta):
2) Define the name and description class methods:
@classmethod
@property
def name(cls) -> str:
return "my_name"
@classmethod
@property
def description(cls) -> str:
return "My description"
name() should return a short, distinct, and a valid filename (e.g. "nanogpt, llamba-block").
description() should return a short sentence describing the benchmark (e.g. "NanoGPT's LayerNorm module forward").
2) Define a sequence of BenchmarkArgs the benchmark accepts.
_args = (
BenchmarkArg(...),
BenchmarkArg(...),
)
2) Implement an args() method that returns the sequence of _args.
@classmethod
@property
def args(cls) -> tuple[BenchmarkArg, ...]:
return cls._args
3) Implement the __init__() method.
It should accept a positional parameter for each benchmark arg, in the order
they are returned from args()
def __init__(self, arg0=default0, arg1=default1, ...):
super().__init__(self)
self.devices: list[str] = [dev0, ...]
__init__() should call super().
__init__() should set the "devices" attribute to be a list of all devices (as strings) used
__init__() can accept additional optional parameters, like parameters with default values
or kwargs, but these parameters must be after the benchmark arg parameters.
4) Implement the make_batch() method.
def make_batch(self) -> tuple[list, dict]:
make_batch() should produce a valid input for the benchmark, possibly modified by
the initialization arguments, as a list of args and a dict of kwargs.
5) Implement the fn() method.
def fn(self) -> Callable:
fn() should return a Callable to be benchmarked.
The returned callable must accept the output of make_batch(), and it may be modified depending on
the initialization arguments.
This function typically prints the benchmark's parameters.
6) Optionally implement the postprocess_for_backward() method.
def postprocess_for_backward(self, out: Any) -> Any:
This will be given the output of fn(), and if it returns a torch.Tensor t that requires grad then
the benchmark will call t.backward(torch.randn_like(t)).
By default, postprocess_for_backward() returns the output of fn(), or the first element of
the output of fn() if fn() returns a Sequence.
"""
def __init__(self):
self.devices: list[str] = []
@classmethod
@property
def name(cls) -> str:
raise NotImplementedError
@classmethod
@property
def description(cls) -> str:
raise NotImplementedError
@classmethod
@property
def args(cls) -> tuple[BenchmarkArg, ...]:
raise NotImplementedError
def make_batch(self) -> tuple[list, dict]: # args, kwargs
raise NotImplementedError
def fn(self, *args, **kwargs) -> Callable:
raise NotImplementedError
def postprocess_for_backward(self, out: Any) -> Any:
if isinstance(out, Sequence):
return out[0]
return out
def describe_benchmark(benchmark: type) -> None:
print(f"{benchmark.name}. {benchmark.description}")
print("Arguments:")
for arg in benchmark.args:
print(f"\t{arg.name}. {arg.description}")
# Base class for benchmark executors
class BenchmarkExecutor:
"""
To add a benchmark executor ...
1) Define a make_callable() method:
(self, fn: Callable) -> Callable
That accepts a function fn and returns another function that executes it using a
particular executor (possibly with settings determined by __init__())
2) Add one or more labels to BENCHMARK_EXECUTORS and update _benchmark_executor_map to
map the label or labels to instantiations of the executor
"""
def __init__(self):
pass
def make_callable(self, fn: Callable) -> Callable:
raise NotImplementedError
# NOTE All times are in nanoseconds from epoch
@dataclass
class BenchmarkRunStatistics:
total_time: int
start_time: int
stop_time: int
host_stop_time: int
called_backward: bool
has_extended_stats: bool = False
last_trace_host_start: int = -1
last_trace_host_stop: int = -1
last_trace_cache_start: int = -1
last_trace_cache_stop: int = -1
last_trace_tracing_start: int = -1
last_trace_tracing_stop: int = -1
last_trace_host_execution_start: int = -1
last_trace_host_execution_stop: int = -1
# A timing helper
def _benchmark(
benchmark: Benchmark,
fn: Callable,
wait_for_computation: Callable,
repetitions: int,
*,
use_grad_transform: bool = False,
compile_backward: bool = False,
) -> list[BenchmarkRunStatistics]:
stats = []
for _ in range(repetitions):
# TODO - set grads to none
args, kwargs = benchmark.make_batch()
wait_for_computation()
called_backward: bool = False
start: int = time.perf_counter_ns()
result = fn(*args, **kwargs)
if compile_backward:
# NOTE In this case backward has been compiled, so nothing more to be done
pass
elif use_grad_transform:
# This populates the grads on the module (even though they're cleared in a moment)
# because calling backward() in PyTorch populates the grads, so for a far comparison
# the benchmark needs to account for that happening
if isinstance(fn, torch.nn.Module):
populate_grads(result, fn)
else:
populate_grads(result, args=args, kwargs=kwargs)
else:
# Calls backward, if the output requires grad
grad_tensor = benchmark.postprocess_for_backward(result)
if grad_tensor is not None and isinstance(grad_tensor, torch.Tensor) and grad_tensor.requires_grad:
grad_tensor.backward(torch.ones_like(grad_tensor))
called_backward = True
host_stop: int = time.perf_counter_ns()
wait_for_computation()
stop: int = time.perf_counter_ns()
if isinstance(fn, torch.nn.Module):
clear_grads(fn)
cs = thunder.compile_stats(fn)
stat = BenchmarkRunStatistics(
total_time=(stop - start),
start_time=start,
stop_time=stop,
host_stop_time=host_stop,
called_backward=called_backward,
)
# TODO Ensure the compile data statistics are always populated
if cs is not None and cs.last_trace_host_start > 0:
stat.has_extended_stats = True
stat.last_trace_host_start = cs.last_trace_host_start
stat.last_trace_host_stop = cs.last_trace_host_stop
stat.last_trace_cache_start = cs.last_trace_cache_start
stat.last_trace_cache_stop = cs.last_trace_cache_stop
stat.last_trace_tracing_start = cs.last_trace_tracing_start
stat.last_trace_tracing_stop = cs.last_trace_tracing_stop
stat.last_trace_host_execution_start = cs.last_trace_host_execution_start
stat.last_trace_host_execution_stop = cs.last_trace_host_execution_stop
stats.append(stat)
return stats
# TODO Consider filling a large tensor with zeros in an attempt to prevent caching
def wait_for_cuda_computation() -> None:
torch.cuda.synchronize()
# Prints nanoseconds as microseconds, rounded
def ns_to_us(ns: Number) -> str:
us = "\u03bcs"
return f"{round(ns / 1000):.2e}{us}"
def _prettyprint_stats(
benchmark_name: str,
*,
callable_construction_time: int,
warmup_stats: list[BenchmarkRunStatistics],
benchmark_stats: list[BenchmarkRunStatistics],
extended_printout: bool = True,
rank_mem_info: dict[int, tuple[int, int]] = {},
) -> None:
assert len(warmup_stats) > 0, "Expected at least one warmup run"
assert len(benchmark_stats) > 0, "Expected at least one benchmark run"
# Converts callable construction time, in nanoseconds, to a string (in rounded microseconds)
callable_construction_time_us: str = ns_to_us(callable_construction_time)
# Computes total warmup time, in nanoseconds, and converts it to a string (in rounded microsecnods)
total_warmup_time_ns: int = sum(stat.total_time for stat in warmup_stats)
total_warmup_time_us: str = ns_to_us(total_warmup_time_ns)
# Computes average warmup time
avg_warmup_time_ns: float = total_warmup_time_ns / len(warmup_stats)
avg_warmup_time_us: str = ns_to_us(avg_warmup_time_ns)
# Identifies the median benchmark run
sorted_benchmark_stats = sorted(benchmark_stats, key=lambda x: x.total_time)
median_benchmark_stat: BenchmarkRunStatistics
# Handles the case where there are an odd number of benchmark stats (median is the "middle" run)
if len(sorted_benchmark_stats) % 2 == 1:
median_benchmark_stat = sorted_benchmark_stats[len(sorted_benchmark_stats) // 2]
median_benchmark_time_ns = median_benchmark_stat.total_time
else:
# Handles the case where there is an even number of benchmark stats (median is the average of the two "middle" runs)
# NOTE In this case, while we compute the median as expected, we pick the "left middle" as the "representative"
# median run for extended statistic analysis
right_middle: int = len(sorted_benchmark_stats) // 2
left_middle: int = right_middle - 1
left_stat: BenchmarkRunStatistics = sorted_benchmark_stats[left_middle]
right_stat: BenchmarkRunStatistics = sorted_benchmark_stats[right_middle]
median_benchmark_time_ns: int = (left_stat.total_time + right_stat.total_time) // 2
median_benchmark_stat = left_stat
median_benchmark_time_us: str = ns_to_us(median_benchmark_time_ns)
# Computes the average benchmark run time and estimates initialization time
total_backward_calls: int = sum(stat.called_backward for stat in benchmark_stats)
total_benchmark_time_ns: int = sum(stat.total_time for stat in benchmark_stats)
avg_benchmark_time_ns = total_benchmark_time_ns / len(benchmark_stats)
initialization_estimate_ns: float = (avg_warmup_time_ns - avg_benchmark_time_ns) * len(warmup_stats)
initialization_estimate_us: str = ns_to_us(initialization_estimate_ns)
total_initialization_time_ns: float = callable_construction_time + initialization_estimate_ns
total_initialization_time_us: str = ns_to_us(total_initialization_time_ns)
callable_construction_percentage: str = f"{round(callable_construction_time / total_initialization_time_ns * 100)}%"
initialization_percentage: str = f"{round(initialization_estimate_ns / total_initialization_time_ns * 100)}%"
total_time_ns: int = total_warmup_time_ns + total_benchmark_time_ns
total_time_us: str = ns_to_us(total_time_ns)
total_host_time_ns: int = median_benchmark_stat.host_stop_time - median_benchmark_stat.start_time
total_host_time_us: str = ns_to_us(total_host_time_ns)
host_time_percentage: str = f"{round(total_host_time_ns / median_benchmark_stat.total_time * 100)}%"
if not extended_printout:
short_printout = f"""\
{benchmark_name} benchmark results:
The median time of {len(benchmark_stats)} benchmark iterations is {median_benchmark_time_us}.
"""
if rank_mem_info:
short_printout += "\n " + "*" * 20 + " Memory Usage " + "*" * 20
for rank, (memory_allocated, memory_reserved) in rank_mem_info.items():
short_printout += f"\n rank-{rank} - peak allocated memory {memory_allocated / 1024 / 1024:.2f}MB, peak reserved: {memory_reserved / 1024 / 1024:.2f}MB"
short_printout += "\n"
print(short_printout)
return
preamble = f"""\
{benchmark_name} benchmark results:
The median time of {len(benchmark_stats)} benchmark iterations is {median_benchmark_time_us}.
The estimated callable construction and initialization time is {total_initialization_time_us}.
The median benchmark run's host time is {total_host_time_us}, {host_time_percentage} of the total time.
Constructing the callable took {callable_construction_time_us}, {callable_construction_percentage} of the total construction and initialization time.
The estimated initialization time is {initialization_estimate_us}, {initialization_percentage} of the total construction and initialization time.
The total time taken by {len(warmup_stats)} warmup iterations is {total_warmup_time_us} (an average of {avg_warmup_time_us} per iteration).
The total time to run all the iterations (warmup and benchmark) was is {total_time_us}.
The benchmark called backward() {total_backward_calls} times.
"""
if rank_mem_info:
short_printout += "\n " + "*" * 20 + " Memory Usage " + "*" * 20
for rank, (memory_allocated, memory_reserved) in rank_mem_info.items():
short_printout += f"\n rank-{rank} - peak allocated memory {memory_allocated / 1024 / 1024:.2f}MB, peak reserved: {memory_reserved / 1024 / 1024:.2f}MB"
short_printout += "\n"
if median_benchmark_stat.has_extended_stats:
# NOTE At this point in the program extended statistics are available
trace_time_ns = median_benchmark_stat.last_trace_host_stop - median_benchmark_stat.last_trace_host_start
cache_time_ns = median_benchmark_stat.last_trace_cache_stop - median_benchmark_stat.last_trace_cache_start
tracing_time_ns = median_benchmark_stat.last_trace_tracing_stop - median_benchmark_stat.last_trace_tracing_start
trace_execution_time_ns = (
median_benchmark_stat.last_trace_host_execution_stop - median_benchmark_stat.last_trace_host_execution_start
)
trace_time_us: str = ns_to_us(trace_time_ns)
cache_time_us: str = ns_to_us(cache_time_ns)
tracing_time_us: str = ns_to_us(tracing_time_ns)
trace_execution_time_us: str = ns_to_us(trace_execution_time_ns)
trace_time_percentage: str = f"{round(trace_time_ns / median_benchmark_stat.total_time * 100)}%"
cache_time_percentage: str = f"{round(cache_time_ns / median_benchmark_stat.total_time * 100)}%"
tracing_time_percentage: str = f"{round(tracing_time_ns / median_benchmark_stat.total_time * 100)}%"
trace_execution_time_percentage: str = (
f"{round(trace_execution_time_ns / median_benchmark_stat.total_time * 100)}%"
)
before_trace_time_ns = median_benchmark_stat.last_trace_host_start - median_benchmark_stat.start_time
accelerator_wait_time_ns = median_benchmark_stat.stop_time - median_benchmark_stat.last_trace_host_stop
before_trace_time_us: str = ns_to_us(before_trace_time_ns)
accelerator_wait_time_us: str = ns_to_us(accelerator_wait_time_ns)
before_trace_time_percentage: str = f"{round(before_trace_time_ns / median_benchmark_stat.total_time * 100)}%"
accelerator_wait_time_percentage: str = (
f"{round(accelerator_wait_time_ns / median_benchmark_stat.total_time * 100)}%"
)
extension = f"""\
The median benchmark took {before_trace_time_us} to get into the tracing logic, {before_trace_time_percentage} of the total time.
The median benchmark took {accelerator_wait_time_us} waiting for the accelerator's computation to finish, {accelerator_wait_time_percentage} of the total time.
The median benchmark run's total time in tracing logic is {trace_time_us}, {trace_time_percentage} of the total time.
The median benchmark run's cache lookup time is {cache_time_us}, {cache_time_percentage} of the total time.
The median benchmark run's time spent tracing is {tracing_time_us}, {tracing_time_percentage} of the total time.
The median benchmark run's time to request the traced program be executed is {trace_execution_time_us}, {trace_execution_time_percentage} of the total time.
"""
else:
extension = ""
output = textwrap.dedent(preamble) + textwrap.indent(textwrap.dedent(extension), " " * 4)
print(output)
def print_rank_0(message):
"""If distributed is initialized, print only on rank 0."""
if torch.distributed.is_initialized():
if torch.distributed.get_rank() == 0:
print(message)
else:
print(message)
# TODO Consider isolating each benchmark run in a subprocess to avoid cache reuse across benchmarks
# (which has been observed, to get around this just run one benchmark at a time)
def _run_benchmark(
benchmark: Benchmark,
constructor: Callable,
*,
warmup_iters: int = 10,
benchmark_iters: int = 20,
use_grad_transform: bool = False,
compile_backward: bool = False,
) -> tuple[int, list, list, int, int]:
# Determines the "wait for computation function," to be run after calls to make_batch() and the benchmark
# function to ensure that computation has finished
devices: list[str] = benchmark.devices
def wait_for_computation_fn():
return None
for device in devices:
device: thunder.core.devices.Device = thunder.core.devices.device_from_string(device)
if device.devicetype is thunder.core.devices.DeviceType.CUDA:
wait_for_computation_fn = wait_for_cuda_computation
break
# Creates a batch to initialize the device being used for the benchmark
benchmark.make_batch()
wait_for_computation_fn()
# Measures the construction of the callable
# NOTE Callable construction probably doesn't use an accelerator, but this waits for the accelerator
# to finish its work just incase
benchmark_fn = benchmark.fn()
wait_for_computation_fn()
start_time: int = time.perf_counter_ns()
assert not use_grad_transform or not compile_backward, "Can't set both use_grad_transform and compile_backward!"
if use_grad_transform:
benchmark_callable = constructor(benchmark_fn)
benchmark_callable = grad(benchmark_callable)
elif compile_backward:
def _fn(*args, **kwargs):
result = benchmark_fn(*args, **kwargs)
grad_tensor = benchmark.postprocess_for_backward(result)
grad_tensor.backward(torch.ones_like(grad_tensor))
benchmark_callable = constructor(_fn)
else:
benchmark_callable = constructor(benchmark_fn)
wait_for_computation_fn()
stop_time: int = time.perf_counter_ns()
callable_construction_time: int = stop_time - start_time
my_benchmark = partial(
_benchmark,
benchmark,
benchmark_callable,
wait_for_computation_fn,
use_grad_transform=use_grad_transform,
compile_backward=compile_backward,
)
# Performs warmup iters
warmup_stats: list[BenchmarkRunStatistics] = my_benchmark(warmup_iters)
# Benchmarks
cur_dev = torch.cuda.current_device()
torch.cuda.reset_peak_memory_stats(cur_dev)
benchmark_stats: list[BenchmarkRunStatistics] = my_benchmark(benchmark_iters)
memory_stats = torch.cuda.memory_stats(cur_dev)
memory_allocated = memory_stats["allocated_bytes.all.peak"]
memory_reserved = memory_stats["reserved_bytes.all.peak"]
return callable_construction_time, warmup_stats, benchmark_stats, memory_allocated, memory_reserved
# TODO Support for grad transforming the benchmarks is currently a prototype
# Reconcile the grad transform and calling torch.autograd.grad so they can be directly compared
def run_benchmark(
benchmark: Benchmark,
constructor: Callable,
*,
warmup_iters: int = 10,
benchmark_iters: int = 20,
use_grad_transform: bool = False,
extended_printout: bool = True,
compile_backward: bool = False,
) -> None:
print(f"Running benchmark {benchmark.name}")
_print_benchmark_arguments(benchmark)
devices: list[str] = benchmark.devices
if len(devices) == 0:
raise RuntimeError("Found a benchmark with no specified devices")
callable_construction_time, warmup_stats, benchmark_stats, _ = _run_benchmark(
benchmark,
constructor,
warmup_iters=warmup_iters,
benchmark_iters=benchmark_iters,
use_grad_transform=use_grad_transform,
compile_backward=compile_backward,
)
_prettyprint_stats(
benchmark.name,
callable_construction_time=callable_construction_time,
warmup_stats=warmup_stats,
benchmark_stats=benchmark_stats,
extended_printout=extended_printout,
)
# TODO Extend this to work with CPU devices, too
def ddp_runner(args):
init_method, world_size, rank, benchmark, ddp_constructor, warmup_iters, benchmark_iters = args
torch.distributed.init_process_group(
init_method=init_method,
backend="nccl",
rank=rank,
world_size=world_size,
)
benchmark.device = f"cuda:{rank}"
torch.cuda.set_device(rank)
import os
os.environ["LOCAL_RANK"] = str(rank)
stats = _run_benchmark(benchmark, ddp_constructor(rank), warmup_iters=warmup_iters, benchmark_iters=benchmark_iters)
return rank, stats
# TODO Consider muting processes other than rank 0 by redirecting their stdout to devnull
def run_multiprocess_benchmark(
benchmark: Benchmark,
ddp_constructor: Callable,
*,
world_size: int = 2,
warmup_iters: int = 10,
benchmark_iters: int = 20,
extended_printout: bool = True,
) -> tuple[int, Sequence[BenchmarkRunStatistics], Sequence[BenchmarkRunStatistics], dict[int, tuple[int, int]]]:
print(f"Running distributed benchmark {benchmark.name} with {world_size=}")
_print_benchmark_arguments(benchmark)
assert torch.distributed.is_available(), (
"Trying to run a distributed benchmark, but torch.distributed is not available"
)
# Ensures the benchmark is running on a single CUDA device (which is overridden later)
assert (
len(benchmark.devices) == 1
and Devices.device_from_string(benchmark.devices[0]).devicetype == Devices.DeviceType.CUDA
), "Distributed benchmarking currently only supports benchmarks that run on a single CUDA device"
# Ensures the benchmark returns a module (because ddp is only supported on modules)
benchmark_fn = benchmark.fn()
assert isinstance(benchmark_fn, torch.nn.Module), (
"Distributed benchmarking currently only supports module benchmarks"
)
# Validates world size
assert world_size <= torch.cuda.device_count(), (
f"Requested world size of {world_size} is greater than the number of available cuda devices {torch.cuda.device_count()}"
)
FILE_SCHEMA: str = "file://"
if sys.platform == "win32":
FILE_SCHEMA = "file:///"
file_name = tempfile.NamedTemporaryFile(delete=False).name
init_method = f"{FILE_SCHEMA}{file_name}"
input_data = [
(init_method, world_size, rank, benchmark, ddp_constructor, warmup_iters, benchmark_iters)
for rank in range(world_size)
]
from concurrent.futures import ProcessPoolExecutor as Pool
# NOTE This uses the ProcessPoolExecutor because that allows spawning processes within worker threads
# which dynamo relies on
# TODO Consider adding a timeout (possibly configurable when calling run_multiprocess_benchmark())
# TODO In Python 3.11+ ProcessPoolExecutor has the max_tasks_per_child parameter
# which this should set to 1
# TODO Consider defining our own multiprocessing pool that uses max_tasks_per_child and supports dynamo
try:
pool = Pool(mp_context=mp.get_context("spawn"))
results = pool.map(ddp_runner, input_data)
# Aggregates statistics
total_cct: int = 0
all_warmup_stats = []
all_benchmark_stats = []
rank_mem_info = {}
for rank, (
callable_construction_time,
warmup_stats,
benchmark_stats,
memory_allocated,
memory_reserved,
) in results:
total_cct += callable_construction_time
all_warmup_stats.extend(warmup_stats)
all_benchmark_stats.extend(benchmark_stats)
rank_mem_info[rank] = (memory_allocated, memory_reserved)
avg_cct: int = total_cct // world_size
_prettyprint_stats(
benchmark_name=f"{benchmark.name}",
callable_construction_time=avg_cct,
warmup_stats=all_warmup_stats,
benchmark_stats=all_benchmark_stats,
extended_printout=extended_printout,
rank_mem_info=rank_mem_info,
)
finally:
pool.shutdown()
return total_cct, all_warmup_stats, all_benchmark_stats, rank_mem_info
#
# Common executors (defined here for convenience)
#
def torch_executor(fn: Callable) -> Callable:
torch.backends.cuda.matmul.allow_tf32 = True
return fn
def torch_compile_executor(fn: Callable) -> Callable:
torch.backends.cuda.matmul.allow_tf32 = True
torch._dynamo.reset()
return torch.compile(fn)
def thunderfx_executor(fn: Callable) -> Callable:
torch.backends.cuda.matmul.allow_tf32 = True
backend = thunder.dynamo.thunderfx
torch._dynamo.reset()
return backend(fn)
def thunder_torch_executor(fn: Callable) -> Callable:
torch.backends.cuda.matmul.allow_tf32 = True
return thunder.jit(fn, executors=[thunder.pytorch_executor])
def thunder_torch_compile_executor(fn: Callable) -> Callable:
torch.backends.cuda.matmul.allow_tf32 = True
return thunder.jit(fn, executors=[torch_compile_ex])
thunder_apex_executor: None | Callable = None
thunder_apex_nvfuser_executor: None | Callable = None
if apex_entropy_available():
def thunder_apex_executor(fn: Callable) -> Callable:
torch.backends.cuda.matmul.allow_tf32 = True
return thunder.jit(fn, executors=[apex_ex])
def thunder_apex_nvfuser_executor(fn: Callable) -> Callable:
torch.backends.cuda.matmul.allow_tf32 = True
return thunder.jit(fn, executors=[apex_ex, thunder.nvfuser_executor])
thunder_cudnn_executor: None | Callable = None
thunder_cudnn_nvfuser_executor: None | Callable = None
thunder_cudnn_layer_norm_executor: None | Callable = None
thunder_cudnn_layer_norm_nvfuser_executor: None | Callable = None
if cudnn_available():
def thunder_cudnn_executor(fn: Callable) -> Callable:
torch.backends.cuda.matmul.allow_tf32 = True
return thunder.jit(fn, executors=[cudnn_ex])
def thunder_cudnn_nvfuser_executor(fn: Callable) -> Callable:
torch.backends.cuda.matmul.allow_tf32 = True
return thunder.jit(fn, executors=[cudnn_ex, thunder.nvfuser_executor])
def thunder_cudnn_layer_norm_executor(fn: Callable) -> Callable:
torch.backends.cuda.matmul.allow_tf32 = True
return thunder.jit(fn, executors=[cudnn_layernorm_ex])
def thunder_cudnn_layer_norm_nvfuser_executor(fn: Callable) -> Callable:
torch.backends.cuda.matmul.allow_tf32 = True
return thunder.jit(fn, executors=[cudnn_layernorm_ex, thunder.nvfuser_executor])
thunder_transformerengine_executor: None | Callable = None
if transformer_engine_ex is not None:
def thunder_transformerengine_executor(fn: Callable):
return thunder.jit(
fn,
executors=(transformer_engine_ex,) + thunder.get_default_executors(),
transforms=[
TransformerEngineTransform(),
],
)
def thunder_sdpa_executor(fn: Callable) -> Callable:
torch.backends.cuda.matmul.allow_tf32 = True
return thunder.jit(fn, executors=[sdpa_ex])
def thunder_sdpa_torch_compile_nvfuser_executor(fn: Callable) -> Callable:
torch.backends.cuda.matmul.allow_tf32 = True
return thunder.jit(fn, executors=[sdpa_ex, torch_compile_cat_ex, thunder.nvfuser_executor])
def default_torch_ddp_executor(_) -> Callable:
def func(fn: Callable) -> Callable:
torch.backends.cuda.matmul.allow_tf32 = True
return torch.nn.parallel.DistributedDataParallel(fn)
return func
@dataclass(frozen=True)
class get_default_torch_fsdp_executor:
apply_torch_compile: bool
auto_wrap_policy: Any | None
def __call__(self, _) -> Callable:
def func(fn: Callable) -> Callable:
from torch.distributed.fsdp import FullyShardedDataParallel as FSDP
torch.backends.cuda.matmul.allow_tf32 = True
if not self.apply_torch_compile:
return FSDP(fn, sharding_strategy=self.sharding_strategy, auto_wrap_policy=self.auto_wrap_policy)
else:
return torch.compile(
FSDP(
fn,
sharding_strategy=self.sharding_strategy,
use_orig_params=True,
auto_wrap_policy=self.auto_wrap_policy,
)
)
return func
def default_torch_compile_ddp_executor(_) -> Callable:
def func(fn: Callable) -> Callable:
torch.backends.cuda.matmul.allow_tf32 = True
torch._dynamo.reset()
return torch.compile(torch.nn.parallel.DistributedDataParallel(fn))
return func
def default_thunder_torch_executor(fn: Callable) -> Callable:
from thunder.executors import TORCH
torch.backends.cuda.matmul.allow_tf32 = True
return thunder.jit(fn, executors=[TORCH])
def default_thunder_always_trace_executor(fn: Callable) -> Callable:
torch.backends.cuda.matmul.allow_tf32 = True
return thunder.jit(fn, cache="always trace")
def default_thunder_dynamic_strides_executor(fn: Callable) -> Callable:
torch.backends.cuda.matmul.allow_tf32 = True
return thunder.jit(fn)
thunder_executor = default_thunder_dynamic_strides_executor
@dataclass(frozen=True)
class get_default_thunder_ddp_dynamic_strides_executor:
bucket_size_in_mb: float = 25
def __call__(self, _) -> Callable:
from thunder.distributed import ddp
def func(fn: Callable) -> Callable:
torch.backends.cuda.matmul.allow_tf32 = True
return thunder.jit(
ddp(fn, bucket_size_in_mb=self.bucket_size_in_mb),
executors=[
sdpa_ex,
torch_compile_cat_ex,
thunder.nvfuser_executor,
],
)
return func
@dataclass(frozen=True)
class get_default_thunder_fsdp_dynamic_strides_executor:
from thunder.distributed import FSDPBucketingStrategy
from thunder.distributed import FSDPType
bucketing_strategy: FSDPBucketingStrategy
sharding_strategy: FSDPType
def __call__(self, _) -> Callable:
from thunder.distributed import fsdp
def func(fn: Callable) -> Callable:
torch.backends.cuda.matmul.allow_tf32 = True
return thunder.jit(
fsdp(
fn,
bucketing_strategy=self.bucketing_strategy,
sharding_strategy=self.sharding_strategy,
),
executors=[
sdpa_ex,
torch_compile_cat_ex,
thunder.nvfuser_executor,
],
)
return func
def default_thunder_dynamic_strides_executor_no_grad(fn: Callable) -> Callable:
torch.backends.cuda.matmul.allow_tf32 = True
return thunder.jit(fn)
def default_thunder_fixed_executor(fn: Callable) -> Callable:
torch.backends.cuda.matmul.allow_tf32 = True
return thunder.jit(fn, cache="same input")
# TODO Add grad support
def default_thunder_triton_executor(fn: Callable) -> Callable:
torch.backends.cuda.matmul.allow_tf32 = True
TRITON_AVAILABLE = package_available("triton")
assert TRITON_AVAILABLE, "Trying to benchmark with the thunder+triton executor, but triton is not available"
from thunder.executors.triton_crossentropy import register_triton_entropyex
register_triton_entropyex(add_to_default_executors=False)
executors_list = ("triton_crossentropy", executors.NVFUSER, executors.TORCH)
return thunder.jit(fn, executors=executors_list, disable_torch_autograd=True)
# TODO Add grad support
def default_thunder_apex_executor(fn: Callable) -> Callable:
torch.backends.cuda.matmul.allow_tf32 = True
APEX_CROSS_ENTROPY_AVAILABLE = package_available("xentropy_cuda")
assert APEX_CROSS_ENTROPY_AVAILABLE, "Trying to benchmark with the thunder+apex executor, but apex is not available"
from thunder.executors.apex_entropyex_impl import register_apex_entropyex
register_apex_entropyex(add_to_default_executors=False)
executors_list = ("apex_xentropy", executors.NVFUSER, executors.TORCH)
return thunder.jit(fn, executors=executors_list, disable_torch_autograd=True)
# TODO Add grad support
def default_thunder_cudnn_executor(fn: Callable) -> Callable:
torch.backends.cuda.matmul.allow_tf32 = True
assert package_available("cudnn"), "Trying to benchmark with the thunder+cudnn executor, but cudnn is not available"
from thunder.executors.cudnnex import register_cudnnex
register_cudnnex(add_to_default_executors=False)
# executors_list = ("cudnn", executors.NVFUSER, executors.TORCH)
return thunder.jit(fn, executors=executors, disable_torch_autograd=True)
# TODO Add grad support
def default_thunder_cudagraphs_executor(fn: Callable) -> Callable:
torch.backends.cuda.matmul.allow_tf32 = True
executors_list = []
# Adds the Apex executor, if available
APEX_CROSS_ENTROPY_AVAILABLE = package_available("xentropy_cuda")
if APEX_CROSS_ENTROPY_AVAILABLE:
from thunder.executors.apex_entropyex_impl import register_apex_entropyex
register_apex_entropyex(add_to_default_executors=False)
executors_list.append("apex_xentropy")
executors_list.extend((executors.NVFUSER, executors.TORCH))
transforms = [CUDAGraphTransform()]
return thunder.jit(fn, executors=executors_list, transforms=transforms, disable_torch_autograd=True)
#
# Benchmarks
#
# TODO Document a pattern to define benchmarks in another file
def _print_benchmark_arguments(bmark: Benchmark) -> None:
print(f"{bmark.name} benchmark parameters:")
for arg in bmark.args:
print(f"\t{arg.name}={getattr(bmark, arg.name)}")
class StackedAddBenchmark(Benchmark, metaclass=UserFacingBenchmarkMeta):
_args = (
BenchmarkArg(
name="depth",
description="The number of additions to perform. Default is 100.",