-
Notifications
You must be signed in to change notification settings - Fork 122
Expand file tree
/
Copy pathnvfuserex_impl.py
More file actions
3205 lines (2309 loc) · 104 KB
/
Copy pathnvfuserex_impl.py
File metadata and controls
3205 lines (2309 loc) · 104 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
from dataclasses import dataclass, replace
from functools import partial, lru_cache
from numbers import Number
from typing import Any
from collections.abc import Callable, Mapping, Hashable, Sequence
import os
import time
from copy import copy
from itertools import chain, filterfalse
import warnings
from typing import cast
from looseversion import LooseVersion
import torch
from torch import Tensor
IS_TORCH_DISTRIBUTED_AVAILABLE = torch.distributed.is_available()
if IS_TORCH_DISTRIBUTED_AVAILABLE:
from torch.distributed.tensor import DTensor
from torch.distributed.tensor.placement_types import Placement, Shard, Replicate
import torch.distributed as dist
import thunder.core.dtypes as dtypes
import thunder.torch as ltorch
from thunder.torch import TensorLike
from thunder.core import prims, utils
from thunder.core.baseutils import BoundSymbolInterface
from thunder.core.prims import PrimIDs
from thunder.core.proxies import (
NumberProxy,
Proxy,
TupleProxy,
TensorProxy,
variableify,
unvariableify,
Variable,
pyval,
)
from thunder.core.pytree import tree_map
from thunder.core.rematerialization import rematerialize
from thunder.core.utils import check
from thunder.core.trace import TraceCtx, from_trace, TraceProvenance
from thunder.core.symbol import BoundSymbol, BoundSymbolRHS, Symbol, has_tags
from thunder.core.devices import Device, DeviceType, cpu
from thunder.core.transform_common import dce, cse_single_bsym, replace_redundant_inputs
from thunder.core.profile import annotate_for_profile
from thunder.core.compile_data import get_compile_option
from thunder.torch.experimental.dtensor_torch_and_prims import dtensor_mul_prim, dtensor_reshape_prim
from thunder.torch.experimental.dtensor_proxy import DTensorProxy
from thunder.core.transforms import (
get_grad,
put_grads,
)
from nvfuser.pytorch_utils import (
torch_dtype_to_nvfuser_dtype,
)
from thunder.executors.utils import (
Region,
_input_dtype_check_fused_scaled_dot_product_attention,
_input_shape_check_fused_scaled_dot_product_attention,
_fused_sdp_choice,
SpdaBackend,
)
from thunder.executors.passes import update_fusion_call_ctx
from thunder.extend import FUEL_LEVEL, FusionExecutor, register_executor
from thunder.executors.nvfuserex import nvfuser_version
DTENSOR_SUPPORTED_VERSION = LooseVersion("0.2.28")
if nvfuser_version() >= DTENSOR_SUPPORTED_VERSION:
import nvfuser_direct as nvfd
from nvfuser_direct import FusionDefinition as DirectFusionDefinition
# NOTE This impl file is here because nvFuser may not be available, so it's imported conditionally
# by nvfuserex.py when nvFuser is available.
import nvfuser
from nvfuser import DataType, FusionDefinition
#
# Helper functions
#
_lcdtype_to_nvdtype_map: dict[None | type | dtypes.dtype, DataType] = {
dtypes.complex128: DataType.ComplexDouble,
dtypes.complex64: DataType.ComplexFloat,
dtypes.float64: DataType.Double,
dtypes.float32: DataType.Float,
dtypes.float16: DataType.Half,
dtypes.bfloat16: DataType.BFloat16,
dtypes.int64: DataType.Int,
dtypes.int32: DataType.Int32,
dtypes.bool8: DataType.Bool,
dtypes.complex128_: DataType.ComplexDouble,
dtypes.complex64_: DataType.ComplexFloat,
dtypes.float64_: DataType.Double,
dtypes.float32_: DataType.Float,
dtypes.float16_: DataType.Half,
dtypes.bfloat16_: DataType.BFloat16,
dtypes.int64_: DataType.Int,
dtypes.int32_: DataType.Int32,
dtypes.bool8_: DataType.Bool,
# Number types
complex: DataType.ComplexDouble,
float: DataType.Double,
int: DataType.Int,
bool: DataType.Bool,
# Null types
None: DataType.Null,
}
if nvfuser_version() >= LooseVersion("0.2.27"):
_lcdtype_to_nvdtype_map.update(
{
dtypes.uint64: DataType.UInt64,
dtypes.uint64_: DataType.UInt64,
}
)
_lcfp8_to_nvfp8_map: dict[dtypes.dtype, DataType] = {
dtypes.float8_e5m2: DataType.Float8_e5m2,
dtypes.float8_e5m2_: DataType.Float8_e5m2,
dtypes.float8_e4m3fn: DataType.Float8_e4m3fn,
dtypes.float8_e4m3fn_: DataType.Float8_e4m3fn,
}
_lcdtype_to_nvdtype_map.update(_lcfp8_to_nvfp8_map)
def lcdtype_to_nvdtype(lcdtype: type | dtypes.dtype) -> DataType:
return _lcdtype_to_nvdtype_map[lcdtype]
# TODO What kind of constants can nvFuser support?
# TODO Is there a better type annotation for an nvConstant?
# TODO Handle devices!
# Helper to map objects to nvFuser fusion definitions
def _define_constant(fd: FusionDefinition, constant: Any) -> Any:
if isinstance(constant, Number):
val = pyval(constant)
nvdtype = lcdtype_to_nvdtype(type(val))
return fd.define_scalar(constant, nvdtype)
if isinstance(constant, (dtypes.dtype, type)):
return lcdtype_to_nvdtype(constant)
if isinstance(constant, Device):
return None
utils.check(False, lambda: f"Cannot translate {constant} of type {type(constant)} into an nvFuser constant")
# inline_number allows returning Number as-is, instead of wrap it as an nvfuser constant.
def getnv(x: Any, fd: FusionDefinition, lc_to_nv_map: dict, inline_number: bool = False) -> Any:
if inline_number and isinstance(x, Number):
return x
elif isinstance(x, Proxy):
return lc_to_nv_map[x]
elif isinstance(x, (Number, dtypes.dtype, type, Device)):
return _define_constant(fd, x)
elif isinstance(x, Sequence):
return tuple(getnv(i, fd, lc_to_nv_map, inline_number) for i in x)
utils.check(False, lambda: f"Cannot translate {x} of type {type(x)} to an nvFuser object")
# TODO Check the CUDA arch?
def is_supported_device(device: Device) -> bool:
utils.check_type(device, Device)
return device.devicetype is DeviceType.CUDA
def is_supported_devicetype(devicetype: DeviceType) -> bool:
utils.check_type(devicetype, DeviceType)
return devicetype is DeviceType.CUDA
_low_precision_floats = (dtypes.float16, dtypes.float16_, dtypes.bfloat16, dtypes.bfloat16_) + tuple(
_lcfp8_to_nvfp8_map.keys()
)
def device_supports_fp8() -> bool:
cuda_major, _ = torch.cuda.get_device_capability()
return cuda_major > 8
def is_supported_dtype(dtype: type | dtypes.dtype, *, allow_low_precision_floats: bool = True) -> bool:
utils.check_type(dtype, (type, dtypes.dtype))
if not allow_low_precision_floats:
if dtype in _low_precision_floats:
return False
return dtype in _lcdtype_to_nvdtype_map and (device_supports_fp8() if dtype in _lcfp8_to_nvfp8_map else True)
def is_supported_tensor(a: TensorProxy, *, allow_low_precision_floats: bool = True) -> bool:
utils.check_type(a, TensorProxy)
devicetype_supported = a.device.devicetype is DeviceType.CUDA or utils.is_cpu_scalar_tensor(a)
dtype_supported = is_supported_dtype(a.dtype)
if not allow_low_precision_floats:
if a.dtype in _low_precision_floats:
return False
rank_supported = a.ndim <= 8
return devicetype_supported and dtype_supported and rank_supported
def is_supported_tensor_or_number(a: TensorProxy | Number) -> bool:
if isinstance(a, (Number, NumberProxy)):
return True
return is_supported_tensor(a)
# Returns True when all arguments given are supported tensors
# Throws an error if any arguments are not tensors
# TODO Add a check for the tensor have > 0 elements?
def are_supported_tensors(*args) -> bool:
return all(is_supported_tensor(arg) for arg in args)
# Returns True when all arguments given are supported tensors or numbers
# Throws an error if any arguments are not numbers or tensors
def are_supported_tensors_or_numbers(*args) -> bool:
for a in args:
if not is_supported_tensor_or_number(a):
return False
return True
#
# Functions related to creating fusions
#
_translation_map: dict[Hashable, Callable] = {}
def get_translator(bsym: BoundSymbol) -> Callable:
return _translation_map[bsym.sym.id]
def register_dtensor_supported(prim_id: int, fn: Callable, checker_fn: Callable) -> None:
if nvfuser_version() < DTENSOR_SUPPORTED_VERSION:
# Only register dtensor ops if supported version is available.
return
register_supported(prim_id, fn, checker_fn)
def multidevice_schedule(fd: FusionDefinition, in_dtensors: list[Proxy]) -> None:
for in_tv, in_dtensor in zip(fd.fusion.inputs(), in_dtensors):
assert isinstance(in_dtensor, DTensorProxy)
# Set the device mesh.
assert in_dtensor.device_mesh.ndim == 1, "nvFuser's Python API only supports 1D meshes."
mesh = nvfd.multidevice.DeviceMesh(in_dtensor.device_mesh.mesh.tolist())
in_tv.set_device_mesh(mesh)
assert len(in_dtensor.placements) == 1, "nvFuser's Python API only supports 1D meshes."
# Split and parallelize.
# When the mesh is multi-dimensional, iterate through the
# placements in descending order of Placement.dim.
placement: Placement = in_dtensor.placements[0]
if placement.is_shard():
dim = cast(Shard, placement).dim
in_tv.split(dim, mesh.size, inner_split=False)
in_tv.axis(dim).parallelize(nvfd.ParallelType.mesh_x)
in_tv.set_allocation_domain(in_tv.get_loop_domain(), new_contiguity=True)
def create_fd(
bsyms: list[BoundSymbol],
input_descriptors: Sequence[type | tuple[tuple[int, ...], tuple[bool, ...], tuple[int, ...]]],
sorted_unique_inputs: list[Proxy],
sorted_unique_outputs: list[Proxy],
) -> FusionDefinition:
lc_to_nv_map = utils.ProxyDict()
def definition(fd):
# NOTE Adding constants is disabled for the moment in favor of definining them inline
# 0) Adds constants
# for c in constants:
# nv = _define_constant(fd, c)
# lc_to_nv_map[c] = nv
# 1) Inputs are added and mapped to nvFuser objects
# NOTE x is the trace's annotation of the input, y is the actual concrete input descriptor at call time
def add_input(x: Any, y: Any) -> Any:
nv: Any
if isinstance(x, NumberProxy):
nvdtype = lcdtype_to_nvdtype(x.python_type)
nv = fd.define_scalar(nvdtype)
lc_to_nv_map[x] = nv
elif isinstance(x, TensorProxy):
utils.check_type(y, tuple)
contiguity, stride_order, dtensor_metadata = y
symbolic_shape = compute_symbolic_shape(x._shape, x._shape)
nvdtype = lcdtype_to_nvdtype(x.dtype)
is_cpu = x.device == cpu
nv = fd.define_tensor(
shape=symbolic_shape, contiguity=contiguity, dtype=nvdtype, stride_order=stride_order, is_cpu=is_cpu
)
lc_to_nv_map[x] = nv
for idx, s in enumerate(x.shape):
if isinstance(s, Proxy):
lc_to_nv_map[s] = nv.size(idx)
elif isinstance(x, TupleProxy):
# TODO: discuss the contract here on baked in number from a tuple
# TODO: validate x is a tuple of int
nv = fd.define_vector(len(x._value))
lc_to_nv_map[x] = nv
elif isinstance(x, Proxy):
utils.check(False, lambda: f"Unsupported proxy type {type(x)} in fusion", exception_type=AssertionError)
else:
nv = x
lc_to_nv_map[x] = nv
return nv
for pinp, inp in zip(sorted_unique_inputs, input_descriptors):
add_input(pinp, inp)
# 2) Translates bound symbols
def translate_bound_symbol(bsym: BoundSymbol) -> Any:
translator = get_translator(bsym)
nvresults = translator(*bsym.args, **bsym.kwargs, fd=fd, lc_to_nv_map=lc_to_nv_map)
# Updates map
for out, nvout in zip(utils.sequencify(bsym.output), utils.sequencify(nvresults)):
# NOTE out can be None if an operation returned multiple results but only some are used,
# in which case DCE will replace the unused results with None
if out is not None and isinstance(out, Proxy):
lc_to_nv_map[out] = nvout
for bsym in bsyms:
translate_bound_symbol(bsym)
# 3) Adds outputs
# TODO Translate numbers to tensors (and provide the information to translate them back to numbers!)
for out in sorted_unique_outputs:
nvout = lc_to_nv_map[out]
fd.add_output(nvout)
MAX_LENGTH = 9999
if any(isinstance(t, DTensorProxy) for t in sorted_unique_inputs):
# multi-GPU path
utils.check(
all(isinstance(t, DTensorProxy) for t in sorted_unique_inputs),
lambda: "nvfuser: Currently we only support Fusion region with all DTensor inputs or all Tensor inputs but not a mix",
)
def check_dtensor_tracing_and_runtime_metadata(inp):
x, y = inp
_, _, dtensor_metadata = y
runtime_device_mesh_repr = dtensor_metadata[0]
runtime_placements_repr = dtensor_metadata[1]
return x.device_mesh == runtime_device_mesh_repr and x.placements == runtime_placements_repr
utils.check(
all(map(check_dtensor_tracing_and_runtime_metadata, zip(sorted_unique_inputs, input_descriptors))),
lambda: "nvfuser: Expected runtime and tracing metadata to be the same for DTensor.",
)
fd = DirectFusionDefinition()
# Device may be set in one of the "factory" methods like full, iota, or uniform
# NOTE: This should be called before defining because a factory method may look-up at `_selected_device` while being defined.
fd._selected_device = None
with fd:
definition(fd)
multidevice_schedule(fd, sorted_unique_inputs)
else:
# NOTE nvFuser's default max length is 1024 operations at the time of this writing
# This arbitrarily increases it to 9999
# TODO Review splititng very large fusions or removing the max length restriction completely
# See "Very large nvFuser fusions hit max_length"
fd = FusionDefinition(max_length=MAX_LENGTH)
# Device may be set in one of the "factory" methods like full, iota, or uniform
# NOTE: This should be called before defining because a factory method may look-up at `_selected_device` while being defined.
fd._selected_device = None
with fd:
definition(fd)
return fd
def compute_symbolic_shape(
proxy_shape: Sequence[int | NumberProxy], shape: torch.Size | Sequence[int]
) -> tuple[int, ...]:
"""
Computes the symbolic shape of a tensor using nvFuser's notion of a symbolic
shape:
-1s represent symbolic shape in nvfuser;
1s represent broadcast dimensions;
other value represent static shapes in program.
Since nvfuser specializes on size-1 dimension for broadcast, we cannot allow
all dimension to be dynamic. This function looks at TensorProxy.shape as
well as Tensor.shape, and it tries to translate that for nvfuser's
FusionDefinition:
1. if the Tensor.shape entry has value `1`, we translate it as a
constant `1`;
2. else:
2.1 if the corresponding proxy_shape entry is a NumberProxy, we mark
the dimension as dynamic `-1`,
2.2. otherwise, Tensor.shape is translated as a static shape.
Args:
proxy_shape (Sequence[int | NumberProxy]]): The shape property of the
TensorProxy.
shape (Union[torch.Size, Sequence[int]]): The shape of the tensor.
Returns:
Tuple[int, ...]: The shape of the tensor for FusionDefinition.
"""
nvf_shape = []
for p_l, l in zip(proxy_shape, shape):
# loudly raise exception when runtime shape violates proxy_shape in the
# trace, which indicates issues with the cache. This isn't necessarily
# an exception.
check(
isinstance(p_l, NumberProxy) or p_l == l,
lambda: f"inconsistent fusion definition with runtime shape {shape} and trace shape {proxy_shape}",
exception_type=AssertionError,
)
# broadcast is specialized in FusionDefinition, preserve it for correct broadcast semantics
if l == 1:
nvf_shape.append(l)
elif isinstance(p_l, NumberProxy):
nvf_shape.append(-1)
else:
nvf_shape.append(l)
return tuple(nvf_shape)
@lru_cache(maxsize=2048)
def compute_contiguity(
shape: torch.Size | Sequence[int], stride: Sequence[int]
) -> tuple[tuple[bool, ...], tuple[int, ...]]:
"""
Computes the contiguity and stride_order of a tensor using nvFuser's notion.
The contiguity is represented by True, False and None. True represents
dimensions that are contiguous, and False represents dimensions that are not
contiguous, and None represents stride-0 or size-1 dimensions.
The stride_order represents the order of each dimension from innermost to
outermost.
For example, a tensor with shape (1, 2, 3) and stride (6, 3, 1):
contiguity is (None, True, True);
stride_order is (2, 1, 0);
For example, a tensor with shape (2, 3, 4) and stride (12, 1, 3):
contiguity is (True, True, True);
stride_order is (2, 0, 1);
Args:
shape (Union[torch.Size, Sequence[int]]): The shape of the tensor.
stride (Sequence[int]): The stride of the tensor.
Returns:
Tuple[Tuple[bool, ...], Tuple[int, ...]]: The contiguity and stride_order
"""
from nvfuser import compute_tensor_descriptor as nv_compute_td
return tuple(tuple(x) for x in nv_compute_td(shape, stride))
def make_key_from_dtensor(tensor: torch.Tensor) -> tuple:
if IS_TORCH_DISTRIBUTED_AVAILABLE and isinstance(tensor, DTensor):
key = (tensor.device_mesh, tensor.placements)
else:
key = ()
return key
def to_runtime_descriptors(args) -> tuple:
"""
Converts the arguments to their runtime descriptors.
Only Tensor objects are converted to runtime descriptors. Non-Tensor objects
are converted to None.
Args:
args: The arguments to convert.
Returns:
Tuple: The runtime descriptors of the arguments.
"""
return tuple(
compute_contiguity(arg.shape, arg.stride()) + (make_key_from_dtensor(arg),) if isinstance(arg, Tensor) else None
for arg in args
)
# TODO Consider making this just a function, because it's faster to call a function than a callable class
@dataclass(slots=True)
class FusionDefinitionWrapper:
"""
A callable object wrapping a nvFuser fusion definition.
"""
get_fd: Callable[[tuple[type | tuple[tuple[int, ...], tuple[bool, ...], tuple[int, ...]], ...]], FusionDefinition]
to_descriptors: Callable
name: str
use_cache: bool
cache_info: None | Callable = None
cache_clear: None | Callable = None
last_used: None | FusionDefinition = None
last_inputs: None | Sequence[tuple] = None
store_inputs: bool = False
save_fake_inputs: bool = False
enable_options: None | list[str] = None
disable_options: None | list[str] = None
@annotate_for_profile("FusionDefinitionWrapper.__call__")
def __call__(self, *args):
if self.use_cache or self.last_used is None:
self.last_used = self.get_fd(self.to_descriptors(args))
fd = self.last_used
if self.store_inputs:
self.last_inputs = args
if dist.is_available() and any(isinstance(t, torch.distributed.tensor.DTensor) for t in args):
with annotate_for_profile(self.name):
output = nvfd.execute_with_dtensors(fd, args)
return output
else:
with annotate_for_profile(self.name):
return fd.execute(
args,
device=fd._selected_device,
save_repro_inputs=self.save_fake_inputs,
_enable_options=self.enable_options,
_disable_options=self.disable_options,
)
def __repr__(self):
return f"FusionDefinitionWrapper({self.name})"
def all_tagged(bsym: BoundSymbol, tag: prims.OpTags) -> bool:
""":obj:`True` if `bsym` and its subsymbols all are tagged with ``tag``."""
if not has_tags(bsym, {tag}):
return False
for sbsym in bsym.subsymbols:
if not has_tags(sbsym, {tag}):
return False
return True
def create_fusion_definition_wrapper(
bsyms: list[BoundSymbol], name: str, sorted_unique_inputs: list[Proxy], sorted_unique_outputs: list[Proxy]
) -> FusionDefinitionWrapper:
# NOTE Region Inputs and Outputs
# The inputs and outputs to a region are represented as sets, which are sorted by name
# for determinism. Because they're sets, the inputs and outputs to each region are
# unique.
# It's OK to reorder inputs to regions and outputs from regions, become the dataflow of those
# objects is captured by names in the trace.
# These properties are distinct from the inputs and outputs to the trace itself, which
# may contain duplicates and whose order must be preserved.
store_inputs: None | bool = get_compile_option(
"nv_store_fusion_inputs", "Allow nvFuser to store fusion inputs for repro."
)
save_fake_inputs: None | bool = get_compile_option(
"nv_save_fake_inputs", "Allow nvFuser to store fake tensor inputs for repro."
)
enable_options: list[str] = get_compile_option("nv_enable_options", "List of NVFUSER_ENABLE options to set.") or []
disable_options: list[str] = (
get_compile_option("nv_disable_options", "List of NVFUSER_DISABLE options to set.") or []
)
skip_cache: bool = get_compile_option("nv_skip_cache", "Skip cache for nvFuser fusions.") or False
tensor_indices = []
for idx, x in enumerate(sorted_unique_inputs):
if isinstance(x, TensorProxy):
tensor_indices.append(idx)
# NOTE create_fd is an expensive function so we cache using the descriptors of inputs
# TODO (mruberry) We should think how to express "static fusion" that don't need to use
# a cache to improve dispatch performance
@lru_cache(maxsize=2048)
def get_fd(input_descriptors) -> FusionDefinition:
# A closure over local trace and region
return create_fd(bsyms, input_descriptors, sorted_unique_inputs, sorted_unique_outputs)
fdw = FusionDefinitionWrapper(
get_fd,
to_runtime_descriptors,
name,
not skip_cache,
get_fd.cache_info,
get_fd.cache_clear,
store_inputs=store_inputs,
save_fake_inputs=save_fake_inputs,
enable_options=enable_options,
disable_options=disable_options,
)
return fdw
class nvFuserExecutor(FusionExecutor):
# Max number of times that this nvFuserExecutor instance can fuse.
_optimization_fuel: int | FUEL_LEVEL
def __init__(self):
super().__init__("nvfuser", version=nvfuser.version())
# TODO: Replace this with a query to a compile option
self._use_rematerialization = True
fuel_str = os.getenv("NVFUSER_OPTIMIZATION_FUEL")
if fuel_str:
self.set_fuel(int(fuel_str))
else:
self.set_fuel(FUEL_LEVEL.UNLIMITED)
env_var_save_serde = os.getenv("ENABLE_NVFUSER_SERIALIZATION", None)
save_serde: bool = env_var_save_serde in ("true", "1")
self.write_cache_on_exit(save_serde)
def write_cache_on_exit(self, save_cache: bool = False):
"""
Selects whether nvFuser writes its cache when the program exits.
Args:
save_cache (bool): A flag that enables saving nvFuser cache.
Defaults to False.
nvFuser's serialization will save the FusionCache data structure and any
CUDA cubins into a FlatBuffer binary upon exiting the python program.
The binary is stored in /tmp/nvfuser_kernel_db/ with the filename
nvf_serde_[local_rank]_[cuda_major]_[cuda_minor]_[nvrtc_major]_[nvrtc_minor].
Details:
* If the common workspace is exists, nvFuser will load it automatically
when the FusionCache is constructed.
* When this function is enabled, then when the program exits NvFuser
will save the FusionCache, overwritting the previous common workspace.
* If this function is disabled, then when the program exits NvFuser
does nothing. The previous common workspace is preserved if it exists.
* If there are any issues when loading the serialized binary, it is
deleted and the FusionCache is created with its default constructor.
* When the LOCAL_RANK environment variable is set for ddp or fsdp, a
separate fusion cache is saved for each device.
"""
from nvfuser import enable_automatic_serialization, disable_automatic_serialization
if save_cache:
enable_automatic_serialization()
else:
disable_automatic_serialization()
def get_fuel(self, amount: int = 1, /) -> bool:
if self._optimization_fuel is FUEL_LEVEL.UNLIMITED:
return True
if self._optimization_fuel < amount:
return False
self._optimization_fuel -= amount
return True
def set_fuel(self, value: int | FUEL_LEVEL):
if isinstance(value, FUEL_LEVEL):
self._optimization_fuel = value
else:
assert isinstance(value, int)
if value < 0:
raise ValueError(f"optimization_fuel must be non-negative: {value}")
self._optimization_fuel = value
def flatten(self, bsym: BoundSymbol) -> list[BoundSymbol]:
flattened: list[BoundSymbol] = []
# TODO Maybe make this nonrecursive
def _flatten(bsym: BoundSymbol):
nonlocal flattened
if self.can_execute(bsym):
flattened.append(bsym)
return
# NOTE self.can_execute(bsym) is False
check(
len(bsym.subsymbols) > 0,
lambda: f"nvFuser is trying to flatten {bsym} for execution but it's not supported and has no subsymbols",
exception_type=AssertionError,
)
for ssym in bsym.subsymbols:
_flatten(ssym)
_flatten(bsym)
return flattened
def has_cuda_input_or_output(self, bsym: BoundSymbol) -> bool:
for p in chain(bsym.flat_proxy_args, bsym.flat_proxy_outs):
if isinstance(p, TensorProxy) and p.device.devicetype is DeviceType.CUDA:
return True
return False
def _dce_bsyms(self, input_list, output, bsyms: list[BoundSymbol]) -> list[BoundSymbol]:
trace = TraceCtx(None)
trace.bound_symbols = bsyms
bsyms.append(prims.python_return.bind(output, output=None))
needed_proxies: set[Variable] = set()
trace = dce(trace, needed_proxies)
# update the input_list by removing the unused inputs
input_list[:] = [x for x in input_list if variableify(x) in needed_proxies]
return list(filter(lambda x: x.sym != prims.python_return, trace.bound_symbols))
def fuse(self, region: Region, fusion_counter: int) -> BoundSymbol:
sorted_unique_inputs: list[Proxy] = [unvariableify(x) for x in region.inputs]
sorted_unique_outputs: list[Proxy] = [unvariableify(x) for x in region.outputs]
flattened_bsyms: list[BoundSymbol] = []
for bsym in region.bound_symbols:
flattened_bsyms.extend(self.flatten(bsym))
flattened_bsyms = self._dce_bsyms(sorted_unique_inputs, sorted_unique_outputs, flattened_bsyms)
fusion_name = f"nvFusion{fusion_counter}"
annotation = f"{fusion_name}: ({', '.join(bsym.sym.name for bsym in flattened_bsyms)})"
fdw: FusionDefinitionWrapper = create_fusion_definition_wrapper(
flattened_bsyms, annotation, sorted_unique_inputs, sorted_unique_outputs
)
fusion_bsym: BoundSymbol = self.register_temporary_operation(
fusion_name, fdw, inputs=sorted_unique_inputs, outputs=sorted_unique_outputs, bsyms=flattened_bsyms
)
return fusion_bsym
# TODO Update the replacement of redundant proxies to use a visitor pattern
# when that architecture is added in the future
def cse(self, trace: TraceCtx) -> TraceCtx:
"""Remove bound symbols whose right hand side is common expression.
Nvfuser specific CSE pass.
Args:
trace:
Returns:
:class:`TraceCtx` with common subexpression eliminated.
"""
start_time_ns = time.perf_counter_ns()
cse_trace = from_trace(trace)
# The trace_rhs_to_bsym_map is used for CSE on trace outside of nvFusion region.
# TODO: CSE on overall trace should NOT be inside fusion pass for nvfuser executor.
trace_rhs_to_bsym_map: dict[BoundSymbolRHS, BoundSymbolInterface] = {}
# For bound symbols with redundant rhs expressions, map the output proxies to the output proxies of the common bound symbol.
redundant_map: dict[Variable, Proxy] = {}
new_bsyms = {bsym: bsym for bsym in trace.bound_symbols}
# Updates the trace's proxy
def map_redundant(x: Any) -> Any:
if isinstance(x, Proxy):
return redundant_map.get(Variable(x), x)
return x
for bsym in trace.bound_symbols:
if bsym.sym.is_fusion != True:
new_bsyms[bsym] = cse_single_bsym(redundant_map, trace_rhs_to_bsym_map, bsym)
continue
# The fusion_rhs_to_bsym_map is used only for CSE inside a nvFusion region.
fusion_rhs_to_bsym_map: dict[BoundSymbolRHS, BoundSymbolInterface] = {}
# Rematerialization can replace saved intermediates with extra
# computation. In this case, replacing a redundant operation would
# reference an argument that is removed from the fusion's arguments.
# If the original variable does not exist in this fusion bsym's
# arguments, then skip this redundant mapping.
vargs = [variableify(x) for x in bsym.args]
this_fusion_redundant_map = {k: v for k, v in redundant_map.items() if k in vargs}
# Apply cse transformation to subsymbols.
cse_subsymbols = map(
partial(cse_single_bsym, this_fusion_redundant_map, fusion_rhs_to_bsym_map), bsym.subsymbols
)
remove_none_subsymbols = tuple(filterfalse(lambda a: a is None, cse_subsymbols))
new_subsymbols = replace_redundant_inputs(this_fusion_redundant_map, remove_none_subsymbols)
# Add any new redundant mappings for this fusion to the main dictionary.
redundant_map.update(this_fusion_redundant_map)
# Map redundant args and outputs that have a common subexpression to the same value.
# Remove identical values from the bsym's arguments and outputs.
# * First, variableify the proxies so they are hashable.
# * Then, create a dictionary where the keys are variables and the values are their original proxies.
# * Lastly, create a new tuple given the dictionary values.
new_args = tree_map(map_redundant, bsym.args)
if isinstance(new_args, Sequence):
new_args = tuple({variableify(x): x for x in new_args}.values())
new_output = tree_map(map_redundant, bsym.output)
if isinstance(new_output, Sequence):
new_output = tuple({variableify(x): x for x in new_output}.values())
# Create new bsym with updated args, subsymbols and outputs.
new_bsyms[bsym] = replace(bsym, args=new_args, subsymbols=new_subsymbols, output=new_output)
# TODO Add (rhs, bsym) key, value pairs for nvfusion outputs to trace_rhs_to_bsym_map
# New bound symbols are still incorrect. Its _ctx_call dict points to the
# old nvFuser fusion. We need to update it to use the new definition.
new_symbols = [new_bsyms.get(bsym, bsym) for bsym in trace.bound_symbols]
cse_trace.bound_symbols = list(filterfalse(lambda a: a is None, new_symbols))
return_bsym = cse_trace.bound_symbols[-1]
assert return_bsym.sym.id == prims.PrimIDs.RETURN
trace_output = tree_map(map_redundant, return_bsym.args)
cse_trace.bound_symbols[-1] = prims.python_return.bind(*trace_output, output=None)
end_time_ns = time.perf_counter_ns()
elapsed_time_ns = end_time_ns - start_time_ns
elapsed_time_millis = elapsed_time_ns // 1000000
cse_trace.set_provenance(
TraceProvenance(f"Nvfuser Common Subexpression Elimination (took {elapsed_time_millis} milliseconds)")
)
return cse_trace
# TODO Restore fusion logic here -- this just replaces supported operations in isolation at the moment
def fusion_pass(self, trace: TraceCtx) -> TraceCtx:
start_time_ns: int = time.perf_counter_ns()
# Replace uniform with uniform_philox and rng state operators for better rematerialization
from thunder.core.rematerialization import replace_uniform
trace = replace_uniform(trace)
fusedtrace: TraceCtx = from_trace(trace)
producers, consumers = utils.producers_and_consumers(trace)
from thunder.executors.data_dependent_partition import Node, fuse_bound_symbols
fused_bsyms = []
# TODO has_cuda_input_or_output is too restrictive a check on what should be fused
# TODO check whether a function would output a CPU tensor? -- can nvFuser fuse such operations?
# ex. device_put to a CPU device from a CUDA device
def _should_fuse(a: Node, b: Node):
def _can_fuse_node(n: Node):
# if already merged, then node can be fused
if len(n.group_bsyms) > 1:
return True
bsym: BoundSymbol = n.group_bsyms[0]
can_fuse: bool = self.can_fuse(bsym)
cuda_in_or_out: bool = self.has_cuda_input_or_output(bsym)
return can_fuse and cuda_in_or_out
return _can_fuse_node(a) and _can_fuse_node(b)
bound_symbol_groups = fuse_bound_symbols(trace, _should_fuse)
# Counts how many fusions (per executor) have been constructed
# (Used to name fusions like nvFusion0, nvFusion1, ...)
fusion_counter: int = 0
for bsyms in bound_symbol_groups:
# TODO The following allows generating single node fusions, which
# may be suboptimal for real-world performance.
# Provide a mechanism to switch between "test" and "perf" modes
# so that we can continue to generate single node fusions when testing.
# if len(bsyms) > 1:
region = Region(producers, consumers, bsyms)
nv_enable_shape_only_fusion: None | bool = get_compile_option(
"nv_enable_shape_only_fusion",
"Allow nvFuser to create Fusion with shape only operations. Defaults to False.",
)
if not nv_enable_shape_only_fusion:
# Don't fuse a region which has only Shape Operations.
all_shape_ops = all(map(lambda bsym: all_tagged(bsym, prims.OpTags.SHAPE_OP), bsyms))
if all_shape_ops:
fused_bsyms.extend(bsyms)
continue
if len(bsyms) == 1:
bsym: BoundSymbol = bsyms[0]
can_fuse: bool = self.can_fuse(bsym)
cuda_in_or_out: bool = self.has_cuda_input_or_output(bsym)
if not can_fuse or not cuda_in_or_out:
fused_bsyms.append(bsym)
continue
if self.get_fuel():
fusion_bsym: BoundSymbol = self.fuse(region, fusion_counter)
fused_bsyms.append(fusion_bsym)
fusion_counter += 1
else:
fused_bsyms.extend(region.bound_symbols)
fusedtrace.bound_symbols = fused_bsyms
# Some of the operations might be better placed with its consumers (for
# example residual connection in transformer block). This pass moves
# them to the consumer.
if self._use_rematerialization:
fusedtrace = rematerialize(fusedtrace)
fusedtrace = remove_redundant_casts(fusedtrace)
fusedtrace = self.cse(fusedtrace)
fusedtrace = dce(fusedtrace)
fusedtrace = update_fusion_call_ctx(fusedtrace)
end_time_ns: int = time.perf_counter_ns()
elapsed_time_ns: int = end_time_ns - start_time_ns
elapsed_time_millis: int = elapsed_time_ns // 1000000
fusedtrace.set_provenance(TraceProvenance(f"Fusion (took {elapsed_time_millis} milliseconds)"))
return fusedtrace
ex = nvFuserExecutor()
register_executor(ex)
def register_supported(sym_or_id: Hashable, translator: Callable, checker: Callable):
ex.register_supported(sym_or_id, checker)
id = sym_or_id.id if isinstance(sym_or_id, Symbol) else sym_or_id
_translation_map[id] = translator
#
# Data movement operations
#
def _convert_element_type_check(a: TensorProxy | Number, dtype: type | dtypes.dtype) -> bool:
return is_supported_tensor_or_number(a) and is_supported_dtype(dtype)
# TODO Review conversion of numbers vs. tensors
def convert_element_type(
a: TensorProxy | Number, dtype: type | dtypes.dtype, *, fd: FusionDefinition, lc_to_nv_map: dict
) -> Any:
nva = getnv(a, fd, lc_to_nv_map)
nvdtype = lcdtype_to_nvdtype(dtype)
return fd.ops.cast(nva, nvdtype)
register_supported(PrimIDs.CONVERT_ELEMENT_TYPE, convert_element_type, _convert_element_type_check)
#
# Tensor creation operations
#
def _select_device(fd: FusionDefinition, device: None | Device):
"""Specify device for function return values.
The device argument is sometimes provided in factory functions that don't
take inputs, such as `full` or `uniform`. This argument provides a useful
hint for inferring which device to run a Fusion in some cases. Note that if
this is not called, the device will be inferred from inputs or default to
the first CUDA device. If this function is called with an argument other
than `None`, then passing inputs residing on other devices is an error, as
is calling this function with non-`None` arguments multiple times with
incompatible arguments.
"""
if device is None:
return
utils.check(
device.devicetype == DeviceType.CUDA,
lambda: f"If device argument is provided, NVFuser executor requires it to be a CUDA device, but {device=}",
)
if device.index is None:
return