-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathcompiler.html
1320 lines (1053 loc) · 75.4 KB
/
compiler.html
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
<!DOCTYPE html>
<!--[if IE 8]><html class="no-js lt-ie9" lang="en" > <![endif]-->
<!--[if gt IE 8]><!--> <html class="no-js" lang="en" > <!--<![endif]-->
<head>
<meta name="robots" content="noindex">
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>torch.compiler — PyTorch 2.6 documentation</title>
<link rel="canonical" href="https://pytorch.org/docs/stable/_modules/torch/compiler.html"/>
<link rel="stylesheet" href="../../_static/css/theme.css" type="text/css" />
<!-- <link rel="stylesheet" href="../../_static/pygments.css" type="text/css" /> -->
<link rel="stylesheet" href="../../_static/pygments.css" type="text/css" />
<link rel="stylesheet" href="../../_static/css/theme.css" type="text/css" />
<link rel="stylesheet" href="../../_static/copybutton.css" type="text/css" />
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/[email protected]/dist/katex.min.css" type="text/css" />
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/[email protected]/dist/katex.min.css" type="text/css" />
<link rel="stylesheet" href="../../_static/katex-math.css" type="text/css" />
<link rel="stylesheet" href="../../_static/sphinx-dropdown.css" type="text/css" />
<link rel="stylesheet" href="../../_static/panels-bootstrap.min.css" type="text/css" />
<link rel="stylesheet" href="../../_static/css/jit.css" type="text/css" />
<link rel="stylesheet" href="../../_static/css/custom.css" type="text/css" />
<link rel="index" title="Index" href="../../genindex.html" />
<link rel="search" title="Search" href="../../search.html" />
<!-- Google Tag Manager -->
<script>(function(w,d,s,l,i){w[l]=w[l]||[];w[l].push({'gtm.start':
new Date().getTime(),event:'gtm.js'});var f=d.getElementsByTagName(s)[0],
j=d.createElement(s),dl=l!='dataLayer'?'&l='+l:'';j.async=true;j.src=
'https://www.googletagmanager.com/gtm.js?id='+i+dl;f.parentNode.insertBefore(j,f);
})(window,document,'script','dataLayer','GTM-T8XT4PS');</script>
<!-- End Google Tag Manager -->
<script src="../../_static/js/modernizr.min.js"></script>
<!-- Preload the theme fonts -->
<link rel="preload" href="../../_static/fonts/FreightSans/freight-sans-book.woff2" as="font" type="font/woff2" crossorigin="anonymous">
<link rel="preload" href="../../_static/fonts/FreightSans/freight-sans-medium.woff2" as="font" type="font/woff2" crossorigin="anonymous">
<link rel="preload" href="../../_static/fonts/IBMPlexMono/IBMPlexMono-Medium.woff2" as="font" type="font/woff2" crossorigin="anonymous">
<link rel="preload" href="../../_static/fonts/FreightSans/freight-sans-bold.woff2" as="font" type="font/woff2" crossorigin="anonymous">
<link rel="preload" href="../../_static/fonts/FreightSans/freight-sans-medium-italic.woff2" as="font" type="font/woff2" crossorigin="anonymous">
<link rel="preload" href="../../_static/fonts/IBMPlexMono/IBMPlexMono-SemiBold.woff2" as="font" type="font/woff2" crossorigin="anonymous">
<!-- Preload the katex fonts -->
<link rel="preload" href="https://cdn.jsdelivr.net/npm/[email protected]/dist/fonts/KaTeX_Math-Italic.woff2" as="font" type="font/woff2" crossorigin="anonymous">
<link rel="preload" href="https://cdn.jsdelivr.net/npm/[email protected]/dist/fonts/KaTeX_Main-Regular.woff2" as="font" type="font/woff2" crossorigin="anonymous">
<link rel="preload" href="https://cdn.jsdelivr.net/npm/[email protected]/dist/fonts/KaTeX_Main-Bold.woff2" as="font" type="font/woff2" crossorigin="anonymous">
<link rel="preload" href="https://cdn.jsdelivr.net/npm/[email protected]/dist/fonts/KaTeX_Size1-Regular.woff2" as="font" type="font/woff2" crossorigin="anonymous">
<link rel="preload" href="https://cdn.jsdelivr.net/npm/[email protected]/dist/fonts/KaTeX_Size4-Regular.woff2" as="font" type="font/woff2" crossorigin="anonymous">
<link rel="preload" href="https://cdn.jsdelivr.net/npm/[email protected]/dist/fonts/KaTeX_Size2-Regular.woff2" as="font" type="font/woff2" crossorigin="anonymous">
<link rel="preload" href="https://cdn.jsdelivr.net/npm/[email protected]/dist/fonts/KaTeX_Size3-Regular.woff2" as="font" type="font/woff2" crossorigin="anonymous">
<link rel="preload" href="https://cdn.jsdelivr.net/npm/[email protected]/dist/fonts/KaTeX_Caligraphic-Regular.woff2" as="font" type="font/woff2" crossorigin="anonymous">
<link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.15.2/css/all.css" integrity="sha384-vSIIfh2YWi9wW0r9iZe7RJPrKwp6bG+s9QZMoITbCckVJqGCCRhc+ccxNcdpHuYu" crossorigin="anonymous">
</head>
<div class="container-fluid header-holder tutorials-header" id="header-holder">
<div class="container">
<div class="header-container">
<a class="header-logo" href="https://pytorch.org/" aria-label="PyTorch"></a>
<div class="main-menu">
<ul>
<li class="main-menu-item">
<div id="resourcesDropdownButton" data-toggle="resources-dropdown" class="resources-dropdown">
<a class="with-down-arrow">
Learn
</a>
<div class="resources-dropdown-menu">
<a class="nav-dropdown-item" href="https://pytorch.org/get-started">
<span class=dropdown-title>Get Started</span>
<p>Run PyTorch locally or get started quickly with one of the supported cloud platforms</p>
</a>
<a class="nav-dropdown-item" href="https://pytorch.org/tutorials">
<span class="dropdown-title">Tutorials</span>
<p>Whats new in PyTorch tutorials</p>
</a>
<a class="nav-dropdown-item" href="https://pytorch.org/tutorials/beginner/basics/intro.html">
<span class="dropdown-title">Learn the Basics</span>
<p>Familiarize yourself with PyTorch concepts and modules</p>
</a>
<a class="nav-dropdown-item" href="https://pytorch.org/tutorials/recipes/recipes_index.html">
<span class="dropdown-title">PyTorch Recipes</span>
<p>Bite-size, ready-to-deploy PyTorch code examples</p>
</a>
<a class="nav-dropdown-item" href="https://pytorch.org/tutorials/beginner/introyt.html">
<span class="dropdown-title">Intro to PyTorch - YouTube Series</span>
<p>Master PyTorch basics with our engaging YouTube tutorial series</p>
</a>
</div>
</div>
</li>
<li>
<div id="resourcesDropdownButton" data-toggle="resources-dropdown" class="resources-dropdown">
<a class="with-down-arrow">
Ecosystem
</a>
<div class="resources-dropdown-menu">
<a class="nav-dropdown-item" href="https://pytorch.org/ecosystem">
<span class="dropdown-title">Tools</span>
<p>Learn about the tools and frameworks in the PyTorch Ecosystem</p>
</a>
<a class="nav-dropdown-item" href="https://pytorch.org/#community-module">
<span class=dropdown-title>Community</span>
<p>Join the PyTorch developer community to contribute, learn, and get your questions answered</p>
</a>
<a class="nav-dropdown-item" href="https://discuss.pytorch.org/" target="_blank">
<span class=dropdown-title>Forums</span>
<p>A place to discuss PyTorch code, issues, install, research</p>
</a>
<a class="nav-dropdown-item" href="https://pytorch.org/resources">
<span class=dropdown-title>Developer Resources</span>
<p>Find resources and get questions answered</p>
</a>
<a class="nav-dropdown-item" href="https://pytorch.org/ecosystem/contributor-awards-2023">
<span class="dropdown-title">Contributor Awards - 2023</span>
<p>Award winners announced at this year's PyTorch Conference</p>
</a>
</div>
</div>
</li>
<li>
<div id="resourcesDropdownButton" data-toggle="resources-dropdown" class="resources-dropdown">
<a class="with-down-arrow">
Edge
</a>
<div class="resources-dropdown-menu">
<a class="nav-dropdown-item" href="https://pytorch.org/edge">
<span class="dropdown-title">About PyTorch Edge</span>
<p>Build innovative and privacy-aware AI experiences for edge devices</p>
</a>
<a class="nav-dropdown-item" href="https://pytorch.org/executorch-overview">
<span class="dropdown-title">ExecuTorch</span>
<p>End-to-end solution for enabling on-device inference capabilities across mobile and edge devices</p>
</a>
</div>
</div>
</li>
<li class="main-menu-item">
<div id="resourcesDropdownButton" data-toggle="resources-dropdown" class="resources-dropdown">
<a class="with-down-arrow">
Docs
</a>
<div class="resources-dropdown-menu">
<a class="nav-dropdown-item" href="https://pytorch.org/docs/stable/index.html">
<span class="dropdown-title">PyTorch</span>
<p>Explore the documentation for comprehensive guidance on how to use PyTorch</p>
</a>
<a class="nav-dropdown-item" href="https://pytorch.org/pytorch-domains">
<span class="dropdown-title">PyTorch Domains</span>
<p>Read the PyTorch Domains documentation to learn more about domain-specific libraries</p>
</a>
</div>
</div>
</li>
<li>
<div id="resourcesDropdownButton" data-toggle="resources-dropdown" class="resources-dropdown">
<a class="with-down-arrow">
Blogs & News
</a>
<div class="resources-dropdown-menu">
<a class="nav-dropdown-item" href="https://pytorch.org/blog/">
<span class="dropdown-title">PyTorch Blog</span>
<p>Catch up on the latest technical news and happenings</p>
</a>
<a class="nav-dropdown-item" href="https://pytorch.org/community-blog">
<span class="dropdown-title">Community Blog</span>
<p>Stories from the PyTorch ecosystem</p>
</a>
<a class="nav-dropdown-item" href="https://pytorch.org/videos">
<span class="dropdown-title">Videos</span>
<p>Learn about the latest PyTorch tutorials, new, and more </p>
<a class="nav-dropdown-item" href="https://pytorch.org/community-stories">
<span class="dropdown-title">Community Stories</span>
<p>Learn how our community solves real, everyday machine learning problems with PyTorch</p>
</a>
<a class="nav-dropdown-item" href="https://pytorch.org/events">
<span class="dropdown-title">Events</span>
<p>Find events, webinars, and podcasts</p>
</a>
</div>
</li>
<li>
<div id="resourcesDropdownButton" data-toggle="resources-dropdown" class="resources-dropdown">
<a class="with-down-arrow">
About
</a>
<div class="resources-dropdown-menu">
<a class="nav-dropdown-item" href="https://pytorch.org/foundation">
<span class="dropdown-title">PyTorch Foundation</span>
<p>Learn more about the PyTorch Foundation</p>
</a>
<a class="nav-dropdown-item" href="https://pytorch.org/governing-board">
<span class="dropdown-title">Governing Board</span>
<p></p>
</a>
</div>
</div>
</li>
<li class="main-menu-item">
<div class="no-dropdown">
<a href="https://pytorch.org/join" data-cta="join">
Become a Member
</a>
</div>
</li>
<li>
<div class="main-menu-item">
<a href="https://github.com/pytorch/pytorch" class="github-icon">
</a>
</div>
</li>
<!--- TODO: This block adds the search icon to the nav bar. We will enable it later.
<li>
<div class="main-menu-item">
<a href="https://github.com/pytorch/pytorch" class="search-icon">
</a>
</div>
</li>
--->
</ul>
</div>
<a class="main-menu-open-button" href="#" data-behavior="open-mobile-menu"></a>
</div>
</div>
</div>
<body class="pytorch-body">
<div class="table-of-contents-link-wrapper">
<span>Table of Contents</span>
<a href="#" class="toggle-table-of-contents" data-behavior="toggle-table-of-contents"></a>
</div>
<nav data-toggle="wy-nav-shift" class="pytorch-left-menu" id="pytorch-left-menu">
<div class="pytorch-side-scroll">
<div class="pytorch-menu pytorch-menu-vertical" data-spy="affix" role="navigation" aria-label="main navigation">
<div class="pytorch-left-menu-search">
<div class="version">
<a href='https://pytorch.org/docs/versions.html'>2.6 ▼</a>
</div>
<div id="searchBox">
<div class="searchbox" id="googleSearchBox">
<script async src="https://cse.google.com/cse.js?cx=e65585f8c3ea1440e"></script>
<div class="gcse-search"></div>
</div>
<div id="sphinxSearchBox" style="display: none;">
<div role="search">
<form id="rtd-search-form" class="wy-form" action="../../search.html" method="get">
<input type="text" name="q" placeholder="Search Docs" />
<input type="hidden" name="check_keywords" value="yes" />
<input type="hidden" name="area" value="default" />
</form>
</div>
</div>
</div>
<form id="searchForm">
<label style="margin-bottom: 1rem">
<input type="radio" name="searchType" value="google" checked>
Google Search
</label>
<label style="margin-bottom: 1rem">
<input type="radio" name="searchType" value="sphinx">
Classic Search
</label>
</form>
<script>
document.addEventListener('DOMContentLoaded', function() {
const searchForm = document.getElementById('searchForm');
const googleSearchBox = document.getElementById('googleSearchBox');
const sphinxSearchBox = document.getElementById('sphinxSearchBox');
// Function to toggle search box visibility
function toggleSearchBox(searchType) {
googleSearchBox.style.display = searchType === 'google' ? 'block' : 'none';
sphinxSearchBox.style.display = searchType === 'sphinx' ? 'block' : 'none';
}
// Determine the default search type
let defaultSearchType;
const currentUrl = window.location.href;
if (currentUrl.startsWith('https://pytorch.org/docs/stable')) {
// For the stable documentation, default to Google
defaultSearchType = localStorage.getItem('searchType') || 'google';
} else {
// For any other version, including docs-preview, default to Sphinx
defaultSearchType = 'sphinx';
}
// Set the default search type
document.querySelector(`input[name="searchType"][value="${defaultSearchType}"]`).checked = true;
toggleSearchBox(defaultSearchType);
// Event listener for changes in search type
searchForm.addEventListener('change', function(event) {
const selectedSearchType = event.target.value;
localStorage.setItem('searchType', selectedSearchType);
toggleSearchBox(selectedSearchType);
});
// Set placeholder text for Google search box
window.onload = function() {
var placeholderText = "Search Docs";
var googleSearchboxText = document.querySelector("#gsc-i-id1");
if (googleSearchboxText) {
googleSearchboxText.placeholder = placeholderText;
googleSearchboxText.style.fontFamily = 'FreightSans';
googleSearchboxText.style.fontSize = "1.2rem";
googleSearchboxText.style.color = '#262626';
}
};
});
</script>
<!--temporarily add a link to survey -->
<div class="survey-link">
<p><i class="fas fa-poll" aria-hidden="true">  </i><a href="https://forms.gle/tdrnwJhaQ9tUePxz9">Share Your Feedback</a> about our new search</p>
</div>
</div>
<p class="caption" role="heading"><span class="caption-text">Community</span></p>
<ul>
<li class="toctree-l1"><a class="reference internal" href="../../community/build_ci_governance.html">PyTorch Governance | Build + CI</a></li>
<li class="toctree-l1"><a class="reference internal" href="../../community/contribution_guide.html">PyTorch Contribution Guide</a></li>
<li class="toctree-l1"><a class="reference internal" href="../../community/design.html">PyTorch Design Philosophy</a></li>
<li class="toctree-l1"><a class="reference internal" href="../../community/governance.html">PyTorch Governance | Mechanics</a></li>
<li class="toctree-l1"><a class="reference internal" href="../../community/persons_of_interest.html">PyTorch Governance | Maintainers</a></li>
</ul>
<p class="caption" role="heading"><span class="caption-text">Developer Notes</span></p>
<ul>
<li class="toctree-l1"><a class="reference internal" href="../../notes/amp_examples.html">Automatic Mixed Precision examples</a></li>
<li class="toctree-l1"><a class="reference internal" href="../../notes/autograd.html">Autograd mechanics</a></li>
<li class="toctree-l1"><a class="reference internal" href="../../notes/broadcasting.html">Broadcasting semantics</a></li>
<li class="toctree-l1"><a class="reference internal" href="../../notes/cpu_threading_torchscript_inference.html">CPU threading and TorchScript inference</a></li>
<li class="toctree-l1"><a class="reference internal" href="../../notes/cuda.html">CUDA semantics</a></li>
<li class="toctree-l1"><a class="reference internal" href="../../notes/custom_operators.html">PyTorch Custom Operators Landing Page</a></li>
<li class="toctree-l1"><a class="reference internal" href="../../notes/ddp.html">Distributed Data Parallel</a></li>
<li class="toctree-l1"><a class="reference internal" href="../../notes/extending.html">Extending PyTorch</a></li>
<li class="toctree-l1"><a class="reference internal" href="../../notes/extending.func.html">Extending torch.func with autograd.Function</a></li>
<li class="toctree-l1"><a class="reference internal" href="../../notes/faq.html">Frequently Asked Questions</a></li>
<li class="toctree-l1"><a class="reference internal" href="../../notes/fsdp.html">FSDP Notes</a></li>
<li class="toctree-l1"><a class="reference internal" href="../../notes/get_start_xpu.html">Getting Started on Intel GPU</a></li>
<li class="toctree-l1"><a class="reference internal" href="../../notes/gradcheck.html">Gradcheck mechanics</a></li>
<li class="toctree-l1"><a class="reference internal" href="../../notes/hip.html">HIP (ROCm) semantics</a></li>
<li class="toctree-l1"><a class="reference internal" href="../../notes/large_scale_deployments.html">Features for large-scale deployments</a></li>
<li class="toctree-l1"><a class="reference internal" href="../../notes/modules.html">Modules</a></li>
<li class="toctree-l1"><a class="reference internal" href="../../notes/mps.html">MPS backend</a></li>
<li class="toctree-l1"><a class="reference internal" href="../../notes/multiprocessing.html">Multiprocessing best practices</a></li>
<li class="toctree-l1"><a class="reference internal" href="../../notes/numerical_accuracy.html">Numerical accuracy</a></li>
<li class="toctree-l1"><a class="reference internal" href="../../notes/randomness.html">Reproducibility</a></li>
<li class="toctree-l1"><a class="reference internal" href="../../notes/serialization.html">Serialization semantics</a></li>
<li class="toctree-l1"><a class="reference internal" href="../../notes/windows.html">Windows FAQ</a></li>
</ul>
<p class="caption" role="heading"><span class="caption-text">Language Bindings</span></p>
<ul>
<li class="toctree-l1"><a class="reference internal" href="../../cpp_index.html">C++</a></li>
<li class="toctree-l1"><a class="reference external" href="https://pytorch.org/javadoc/">Javadoc</a></li>
<li class="toctree-l1"><a class="reference internal" href="../../deploy.html">torch::deploy</a></li>
</ul>
<p class="caption" role="heading"><span class="caption-text">Python API</span></p>
<ul>
<li class="toctree-l1"><a class="reference internal" href="../../torch.html">torch</a></li>
<li class="toctree-l1"><a class="reference internal" href="../../nn.html">torch.nn</a></li>
<li class="toctree-l1"><a class="reference internal" href="../../nn.functional.html">torch.nn.functional</a></li>
<li class="toctree-l1"><a class="reference internal" href="../../tensors.html">torch.Tensor</a></li>
<li class="toctree-l1"><a class="reference internal" href="../../tensor_attributes.html">Tensor Attributes</a></li>
<li class="toctree-l1"><a class="reference internal" href="../../tensor_view.html">Tensor Views</a></li>
<li class="toctree-l1"><a class="reference internal" href="../../amp.html">torch.amp</a></li>
<li class="toctree-l1"><a class="reference internal" href="../../autograd.html">torch.autograd</a></li>
<li class="toctree-l1"><a class="reference internal" href="../../library.html">torch.library</a></li>
<li class="toctree-l1"><a class="reference internal" href="../../accelerator.html">torch.accelerator</a></li>
<li class="toctree-l1"><a class="reference internal" href="../../cpu.html">torch.cpu</a></li>
<li class="toctree-l1"><a class="reference internal" href="../../cuda.html">torch.cuda</a></li>
<li class="toctree-l1"><a class="reference internal" href="../../torch_cuda_memory.html">Understanding CUDA Memory Usage</a></li>
<li class="toctree-l1"><a class="reference internal" href="../../torch_cuda_memory.html#generating-a-snapshot">Generating a Snapshot</a></li>
<li class="toctree-l1"><a class="reference internal" href="../../torch_cuda_memory.html#using-the-visualizer">Using the visualizer</a></li>
<li class="toctree-l1"><a class="reference internal" href="../../torch_cuda_memory.html#snapshot-api-reference">Snapshot API Reference</a></li>
<li class="toctree-l1"><a class="reference internal" href="../../mps.html">torch.mps</a></li>
<li class="toctree-l1"><a class="reference internal" href="../../xpu.html">torch.xpu</a></li>
<li class="toctree-l1"><a class="reference internal" href="../../mtia.html">torch.mtia</a></li>
<li class="toctree-l1"><a class="reference internal" href="../../mtia.memory.html">torch.mtia.memory</a></li>
<li class="toctree-l1"><a class="reference internal" href="../../meta.html">Meta device</a></li>
<li class="toctree-l1"><a class="reference internal" href="../../backends.html">torch.backends</a></li>
<li class="toctree-l1"><a class="reference internal" href="../../export.html">torch.export</a></li>
<li class="toctree-l1"><a class="reference internal" href="../../distributed.html">torch.distributed</a></li>
<li class="toctree-l1"><a class="reference internal" href="../../distributed.tensor.html">torch.distributed.tensor</a></li>
<li class="toctree-l1"><a class="reference internal" href="../../distributed.algorithms.join.html">torch.distributed.algorithms.join</a></li>
<li class="toctree-l1"><a class="reference internal" href="../../distributed.elastic.html">torch.distributed.elastic</a></li>
<li class="toctree-l1"><a class="reference internal" href="../../fsdp.html">torch.distributed.fsdp</a></li>
<li class="toctree-l1"><a class="reference internal" href="../../distributed.fsdp.fully_shard.html">torch.distributed.fsdp.fully_shard</a></li>
<li class="toctree-l1"><a class="reference internal" href="../../distributed.tensor.parallel.html">torch.distributed.tensor.parallel</a></li>
<li class="toctree-l1"><a class="reference internal" href="../../distributed.optim.html">torch.distributed.optim</a></li>
<li class="toctree-l1"><a class="reference internal" href="../../distributed.pipelining.html">torch.distributed.pipelining</a></li>
<li class="toctree-l1"><a class="reference internal" href="../../distributed.checkpoint.html">torch.distributed.checkpoint</a></li>
<li class="toctree-l1"><a class="reference internal" href="../../distributions.html">torch.distributions</a></li>
<li class="toctree-l1"><a class="reference internal" href="../../torch.compiler.html">torch.compiler</a></li>
<li class="toctree-l1"><a class="reference internal" href="../../fft.html">torch.fft</a></li>
<li class="toctree-l1"><a class="reference internal" href="../../func.html">torch.func</a></li>
<li class="toctree-l1"><a class="reference internal" href="../../futures.html">torch.futures</a></li>
<li class="toctree-l1"><a class="reference internal" href="../../fx.html">torch.fx</a></li>
<li class="toctree-l1"><a class="reference internal" href="../../fx.experimental.html">torch.fx.experimental</a></li>
<li class="toctree-l1"><a class="reference internal" href="../../hub.html">torch.hub</a></li>
<li class="toctree-l1"><a class="reference internal" href="../../jit.html">torch.jit</a></li>
<li class="toctree-l1"><a class="reference internal" href="../../linalg.html">torch.linalg</a></li>
<li class="toctree-l1"><a class="reference internal" href="../../monitor.html">torch.monitor</a></li>
<li class="toctree-l1"><a class="reference internal" href="../../signal.html">torch.signal</a></li>
<li class="toctree-l1"><a class="reference internal" href="../../special.html">torch.special</a></li>
<li class="toctree-l1"><a class="reference internal" href="../../torch.overrides.html">torch.overrides</a></li>
<li class="toctree-l1"><a class="reference internal" href="../../package.html">torch.package</a></li>
<li class="toctree-l1"><a class="reference internal" href="../../profiler.html">torch.profiler</a></li>
<li class="toctree-l1"><a class="reference internal" href="../../nn.init.html">torch.nn.init</a></li>
<li class="toctree-l1"><a class="reference internal" href="../../nn.attention.html">torch.nn.attention</a></li>
<li class="toctree-l1"><a class="reference internal" href="../../onnx.html">torch.onnx</a></li>
<li class="toctree-l1"><a class="reference internal" href="../../optim.html">torch.optim</a></li>
<li class="toctree-l1"><a class="reference internal" href="../../complex_numbers.html">Complex Numbers</a></li>
<li class="toctree-l1"><a class="reference internal" href="../../ddp_comm_hooks.html">DDP Communication Hooks</a></li>
<li class="toctree-l1"><a class="reference internal" href="../../quantization.html">Quantization</a></li>
<li class="toctree-l1"><a class="reference internal" href="../../rpc.html">Distributed RPC Framework</a></li>
<li class="toctree-l1"><a class="reference internal" href="../../random.html">torch.random</a></li>
<li class="toctree-l1"><a class="reference internal" href="../../masked.html">torch.masked</a></li>
<li class="toctree-l1"><a class="reference internal" href="../../nested.html">torch.nested</a></li>
<li class="toctree-l1"><a class="reference internal" href="../../size.html">torch.Size</a></li>
<li class="toctree-l1"><a class="reference internal" href="../../sparse.html">torch.sparse</a></li>
<li class="toctree-l1"><a class="reference internal" href="../../storage.html">torch.Storage</a></li>
<li class="toctree-l1"><a class="reference internal" href="../../testing.html">torch.testing</a></li>
<li class="toctree-l1"><a class="reference internal" href="../../utils.html">torch.utils</a></li>
<li class="toctree-l1"><a class="reference internal" href="../../benchmark_utils.html">torch.utils.benchmark</a></li>
<li class="toctree-l1"><a class="reference internal" href="../../bottleneck.html">torch.utils.bottleneck</a></li>
<li class="toctree-l1"><a class="reference internal" href="../../checkpoint.html">torch.utils.checkpoint</a></li>
<li class="toctree-l1"><a class="reference internal" href="../../cpp_extension.html">torch.utils.cpp_extension</a></li>
<li class="toctree-l1"><a class="reference internal" href="../../data.html">torch.utils.data</a></li>
<li class="toctree-l1"><a class="reference internal" href="../../deterministic.html">torch.utils.deterministic</a></li>
<li class="toctree-l1"><a class="reference internal" href="../../jit_utils.html">torch.utils.jit</a></li>
<li class="toctree-l1"><a class="reference internal" href="../../dlpack.html">torch.utils.dlpack</a></li>
<li class="toctree-l1"><a class="reference internal" href="../../mobile_optimizer.html">torch.utils.mobile_optimizer</a></li>
<li class="toctree-l1"><a class="reference internal" href="../../model_zoo.html">torch.utils.model_zoo</a></li>
<li class="toctree-l1"><a class="reference internal" href="../../tensorboard.html">torch.utils.tensorboard</a></li>
<li class="toctree-l1"><a class="reference internal" href="../../module_tracker.html">torch.utils.module_tracker</a></li>
<li class="toctree-l1"><a class="reference internal" href="../../type_info.html">Type Info</a></li>
<li class="toctree-l1"><a class="reference internal" href="../../named_tensor.html">Named Tensors</a></li>
<li class="toctree-l1"><a class="reference internal" href="../../name_inference.html">Named Tensors operator coverage</a></li>
<li class="toctree-l1"><a class="reference internal" href="../../config_mod.html">torch.__config__</a></li>
<li class="toctree-l1"><a class="reference internal" href="../../future_mod.html">torch.__future__</a></li>
<li class="toctree-l1"><a class="reference internal" href="../../logging.html">torch._logging</a></li>
<li class="toctree-l1"><a class="reference internal" href="../../torch_environment_variables.html">Torch Environment Variables</a></li>
</ul>
<p class="caption" role="heading"><span class="caption-text">Libraries</span></p>
<ul>
<li class="toctree-l1"><a class="reference external" href="https://pytorch.org/audio/stable">torchaudio</a></li>
<li class="toctree-l1"><a class="reference external" href="https://pytorch.org/data">TorchData</a></li>
<li class="toctree-l1"><a class="reference external" href="https://pytorch.org/torchrec">TorchRec</a></li>
<li class="toctree-l1"><a class="reference external" href="https://pytorch.org/serve">TorchServe</a></li>
<li class="toctree-l1"><a class="reference external" href="https://pytorch.org/text/stable">torchtext</a></li>
<li class="toctree-l1"><a class="reference external" href="https://pytorch.org/vision/stable">torchvision</a></li>
<li class="toctree-l1"><a class="reference external" href="https://pytorch.org/xla/">PyTorch on XLA Devices</a></li>
</ul>
</div>
</div>
</nav>
<div class="pytorch-container">
<div class="pytorch-page-level-bar" id="pytorch-page-level-bar">
<div class="pytorch-breadcrumbs-wrapper">
<div role="navigation" aria-label="breadcrumbs navigation">
<ul class="pytorch-breadcrumbs">
<li>
<a href="../../index.html">
Docs
</a> >
</li>
<li><a href="../index.html">Module code</a> ></li>
<li><a href="../torch.html">torch</a> ></li>
<li>torch.compiler</li>
<li class="pytorch-breadcrumbs-aside">
</li>
</ul>
</div>
</div>
<div class="pytorch-shortcuts-wrapper" id="pytorch-shortcuts-wrapper">
Shortcuts
</div>
</div>
<section data-toggle="wy-nav-shift" id="pytorch-content-wrap" class="pytorch-content-wrap">
<div class="pytorch-content-left">
<!-- Google Tag Manager (noscript) -->
<noscript><iframe src="https://www.googletagmanager.com/ns.html?id=GTM-T8XT4PS"
height="0" width="0" style="display:none;visibility:hidden"></iframe></noscript>
<!-- End Google Tag Manager (noscript) -->
<div class="rst-content">
<div role="main" class="main-content" itemscope="itemscope" itemtype="http://schema.org/Article">
<article itemprop="articleBody" id="pytorch-article" class="pytorch-article">
<h1>Source code for torch.compiler</h1><div class="highlight"><pre>
<span></span><span class="c1"># mypy: allow-untyped-defs</span>
<span class="kn">from</span> <span class="nn">typing</span> <span class="kn">import</span> <span class="n">Any</span><span class="p">,</span> <span class="n">Callable</span><span class="p">,</span> <span class="n">List</span><span class="p">,</span> <span class="n">TypeVar</span>
<span class="kn">import</span> <span class="nn">torch</span>
<span class="n">__all__</span> <span class="o">=</span> <span class="p">[</span>
<span class="s2">"compile"</span><span class="p">,</span>
<span class="s2">"assume_constant_result"</span><span class="p">,</span>
<span class="s2">"reset"</span><span class="p">,</span>
<span class="s2">"allow_in_graph"</span><span class="p">,</span>
<span class="s2">"substitute_in_graph"</span><span class="p">,</span>
<span class="s2">"list_backends"</span><span class="p">,</span>
<span class="s2">"disable"</span><span class="p">,</span>
<span class="s2">"set_stance"</span><span class="p">,</span>
<span class="s2">"cudagraph_mark_step_begin"</span><span class="p">,</span>
<span class="s2">"wrap_numpy"</span><span class="p">,</span>
<span class="s2">"is_compiling"</span><span class="p">,</span>
<span class="s2">"is_dynamo_compiling"</span><span class="p">,</span>
<span class="p">]</span>
<span class="n">_F</span> <span class="o">=</span> <span class="n">TypeVar</span><span class="p">(</span><span class="s2">"_F"</span><span class="p">,</span> <span class="n">bound</span><span class="o">=</span><span class="n">Callable</span><span class="p">[</span><span class="o">...</span><span class="p">,</span> <span class="n">Any</span><span class="p">])</span>
<div class="viewcode-block" id="compile"><a class="viewcode-back" href="../../generated/torch.compiler.compile.html#torch.compiler.compile">[docs]</a><span class="k">def</span> <span class="nf">compile</span><span class="p">(</span><span class="o">*</span><span class="n">args</span><span class="p">,</span> <span class="o">**</span><span class="n">kwargs</span><span class="p">):</span>
<span class="w"> </span><span class="sd">"""</span>
<span class="sd"> See :func:`torch.compile` for details on the arguments for this function.</span>
<span class="sd"> """</span>
<span class="k">return</span> <span class="n">torch</span><span class="o">.</span><span class="n">compile</span><span class="p">(</span><span class="o">*</span><span class="n">args</span><span class="p">,</span> <span class="o">**</span><span class="n">kwargs</span><span class="p">)</span></div>
<div class="viewcode-block" id="reset"><a class="viewcode-back" href="../../generated/torch.compiler.reset.html#torch.compiler.reset">[docs]</a><span class="k">def</span> <span class="nf">reset</span><span class="p">()</span> <span class="o">-></span> <span class="kc">None</span><span class="p">:</span>
<span class="w"> </span><span class="sd">"""</span>
<span class="sd"> This function clears all compilation caches and restores the system to its initial state.</span>
<span class="sd"> It is recommended to call this function, especially after using operations like `torch.compile(...)`</span>
<span class="sd"> to ensure a clean state before another unrelated compilation</span>
<span class="sd"> """</span>
<span class="kn">import</span> <span class="nn">torch._dynamo</span>
<span class="n">torch</span><span class="o">.</span><span class="n">_dynamo</span><span class="o">.</span><span class="n">reset</span><span class="p">()</span></div>
<div class="viewcode-block" id="allow_in_graph"><a class="viewcode-back" href="../../generated/torch.compiler.allow_in_graph.html#torch.compiler.allow_in_graph">[docs]</a><span class="k">def</span> <span class="nf">allow_in_graph</span><span class="p">(</span><span class="n">fn</span><span class="p">):</span>
<span class="w"> </span><span class="sd">"""</span>
<span class="sd"> Tells the compiler frontend (Dynamo) to skip symbolic introspection of the function</span>
<span class="sd"> and instead directly write it to the graph when encountered.</span>
<span class="sd"> If you are using :func:`torch.compile` (with backend="inductor" (the default)), or</span>
<span class="sd"> :func:`torch.export.export`, and trying to black-box a Python function throughout</span>
<span class="sd"> all tracing, do not use this API.</span>
<span class="sd"> Instead, please create a custom operator (see `PyTorch Custom Operators Landing Page</span>
<span class="sd"> <https://pytorch.org/tutorials/advanced/custom_ops_landing_page.html>`_)</span>
<span class="sd"> .. warning::</span>
<span class="sd"> If you're a typical torch.compile user (e.g. you're applying torch.compile to</span>
<span class="sd"> a model to make it run faster), you probably don't want to use this function.</span>
<span class="sd"> :func:`allow_in_graph` is a footgun because it skips the compiler frontend</span>
<span class="sd"> (Dynamo) that is responsible for doing safety checks (graph breaks, handling</span>
<span class="sd"> closures, etc). Incorrect usage will lead to difficult-to-debug silent</span>
<span class="sd"> incorrectness issues.</span>
<span class="sd"> Given a Python function with no allow_in_graph decorator, regular execution</span>
<span class="sd"> of torch.compile traces through the function. :func:`allow_in_graph` changes</span>
<span class="sd"> it so that the frontend does not trace inside the function, but the compiler</span>
<span class="sd"> backend still traces through it. Compare this to custom operators, which</span>
<span class="sd"> treats a function as a black box throughout the torch.compile stack. The following</span>
<span class="sd"> table compares these mechanisms.</span>
<span class="sd"> +------------------------+-----------------------+--------------------------------+</span>
<span class="sd"> | Mechanism | Frontend (Dynamo) | Backend (AOTAutograd+Inductor) |</span>
<span class="sd"> +========================+=======================+================================+</span>
<span class="sd"> | no decorator | trace inside | trace inside |</span>
<span class="sd"> +------------------------+-----------------------+--------------------------------+</span>
<span class="sd"> | allow_in_graph | opaque callable | trace inside |</span>
<span class="sd"> +------------------------+-----------------------+--------------------------------+</span>
<span class="sd"> | custom op | opaque callable | opaque callable |</span>
<span class="sd"> +------------------------+-----------------------+--------------------------------+</span>
<span class="sd"> One common use case for :func:`allow_in_graph()` is as an escape hatch for the compiler</span>
<span class="sd"> frontend: if you know the function works w.r.t. to the downstream components of the</span>
<span class="sd"> compilation stack (AOTAutograd and Inductor) but there is a Dynamo bug that prevents it from</span>
<span class="sd"> symbolically introspecting the function properly (or if your code is in C/C++ and</span>
<span class="sd"> therefore cannot be introspected with Dynamo), then one can decorate said function</span>
<span class="sd"> with :func:`allow_in_graph` to bypass Dynamo.</span>
<span class="sd"> We require that ``fn`` adhere to the following restrictions. Failure to adhere</span>
<span class="sd"> results in undefined behavior:</span>
<span class="sd"> - The inputs to ``fn`` must be Proxy-able types in the FX graph. Valid types include:</span>
<span class="sd"> Tensor/int/bool/float/None/List[Tensor?]/List[int?]/List[float?]</span>
<span class="sd"> Tuple[Tensor?, ...]/Tuple[int?, ...]/Tuple[float?, ...]/torch.dtype/torch.device</span>
<span class="sd"> - The outputs to ``fn`` must be Proxy-able types in the FX graph (see previous bullet)</span>
<span class="sd"> - all Tensors used inside of ``fn`` must be passed directly as inputs to ``fn``</span>
<span class="sd"> (as opposed to being captured variables).</span>
<span class="sd"> Args:</span>
<span class="sd"> fn: A callable representing the function to be included in the graph.</span>
<span class="sd"> If ``fn`` is a list or tuple of callables it recursively applies</span>
<span class="sd"> :func:`allow_in_graph()` to each function and returns a new list or</span>
<span class="sd"> tuple containing the modified functions.</span>
<span class="sd"> Example::</span>
<span class="sd"> torch.compiler.allow_in_graph(my_custom_function)</span>
<span class="sd"> @torch.compile(...)</span>
<span class="sd"> def fn(x):</span>
<span class="sd"> x = torch.add(x, 1)</span>
<span class="sd"> x = my_custom_function(x)</span>
<span class="sd"> x = torch.add(x, 1)</span>
<span class="sd"> return x</span>
<span class="sd"> fn(...)</span>
<span class="sd"> Will capture a single graph containing ``my_custom_function()``.</span>
<span class="sd"> """</span>
<span class="kn">import</span> <span class="nn">torch._dynamo</span>
<span class="k">return</span> <span class="n">torch</span><span class="o">.</span><span class="n">_dynamo</span><span class="o">.</span><span class="n">allow_in_graph</span><span class="p">(</span><span class="n">fn</span><span class="p">)</span></div>
<div class="viewcode-block" id="substitute_in_graph"><a class="viewcode-back" href="../../generated/torch.compiler.substitute_in_graph.html#torch.compiler.substitute_in_graph">[docs]</a><span class="k">def</span> <span class="nf">substitute_in_graph</span><span class="p">(</span>
<span class="n">original_fn</span><span class="p">:</span> <span class="n">_F</span><span class="p">,</span>
<span class="o">*</span><span class="p">,</span>
<span class="n">can_constant_fold_through</span><span class="p">:</span> <span class="nb">bool</span> <span class="o">=</span> <span class="kc">False</span><span class="p">,</span>
<span class="n">skip_signature_check</span><span class="p">:</span> <span class="nb">bool</span> <span class="o">=</span> <span class="kc">False</span><span class="p">,</span>
<span class="p">)</span> <span class="o">-></span> <span class="n">Callable</span><span class="p">[[</span><span class="n">_F</span><span class="p">],</span> <span class="n">_F</span><span class="p">]:</span>
<span class="w"> </span><span class="sd">"""</span>
<span class="sd"> Register a polyfill handler for a function, usually a C function from the C extension, to be</span>
<span class="sd"> used in place of the original function when inlining the original function in the graph.</span>
<span class="sd"> .. note::</span>
<span class="sd"> The polyfill handler is only used when inlining the original function. It is not used when</span>
<span class="sd"> the original function is called directly. In the eager mode, the decorated function calls</span>
<span class="sd"> the performant C function rather than the polyfill handler.</span>
<span class="sd"> The polyfill handler is a function that will be called in place of the original function when</span>
<span class="sd"> inlining the original function. The polyfill handler should have the same signature and the same</span>
<span class="sd"> behavior as the original function.</span>
<span class="sd"> Args:</span>
<span class="sd"> original_fn (callable): The original function, usually a C function, to register a polyfill</span>
<span class="sd"> handler for.</span>
<span class="sd"> can_constant_fold_through (bool, optional): Whether the polyfill handler can be constant</span>
<span class="sd"> folded through. That is, if the polyfill handler is a pure function and its arguments</span>
<span class="sd"> are constant, the result of the polyfill handler can be constant folded during the</span>
<span class="sd"> compilation. Defaults to ``False``.</span>
<span class="sd"> skip_signature_check (bool, optional): Whether to skip the signature check between the</span>
<span class="sd"> original function and the polyfill handler. Defaults to ``False``.</span>
<span class="sd"> Returns:</span>
<span class="sd"> A decorator that registers the polyfill handler for the original function.</span>
<span class="sd"> Example::</span>
<span class="sd"> >>> import operator</span>
<span class="sd"> >>> operator.indexOf([1, 2, 3, 4, 5], 3)</span>
<span class="sd"> 2</span>
<span class="sd"> >>> torch.compile(operator.indexOf, fullgraph=True)([1, 2, 3, 4, 5], 3)</span>
<span class="sd"> ... # xdoctest: +SKIP("Long tracebacks")</span>
<span class="sd"> Traceback (most recent call last):</span>
<span class="sd"> ...</span>
<span class="sd"> torch._dynamo.exc.Unsupported: ...</span>
<span class="sd"> >>> @torch.compiler.substitute_in_graph(operator.indexOf)</span>
<span class="sd"> ... def indexOf(a, b, /):</span>
<span class="sd"> ... for i, item in enumerate(a):</span>
<span class="sd"> ... if item is b or item == b:</span>
<span class="sd"> ... return i</span>
<span class="sd"> ... raise ValueError("sequence.index(x): x not in sequence")</span>
<span class="sd"> >>></span>
<span class="sd"> >>> torch.compile(operator.indexOf, fullgraph=True)([1, 2, 3, 4, 5], 3)</span>
<span class="sd"> 2</span>
<span class="sd"> """</span>
<span class="kn">import</span> <span class="nn">torch._dynamo</span>
<span class="k">return</span> <span class="n">torch</span><span class="o">.</span><span class="n">_dynamo</span><span class="o">.</span><span class="n">substitute_in_graph</span><span class="p">(</span>
<span class="n">original_fn</span><span class="p">,</span>
<span class="n">can_constant_fold_through</span><span class="o">=</span><span class="n">can_constant_fold_through</span><span class="p">,</span>
<span class="n">skip_signature_check</span><span class="o">=</span><span class="n">skip_signature_check</span><span class="p">,</span>
<span class="p">)</span></div>
<div class="viewcode-block" id="list_backends"><a class="viewcode-back" href="../../generated/torch.compiler.list_backends.html#torch.compiler.list_backends">[docs]</a><span class="k">def</span> <span class="nf">list_backends</span><span class="p">(</span><span class="n">exclude_tags</span><span class="o">=</span><span class="p">(</span><span class="s2">"debug"</span><span class="p">,</span> <span class="s2">"experimental"</span><span class="p">))</span> <span class="o">-></span> <span class="n">List</span><span class="p">[</span><span class="nb">str</span><span class="p">]:</span>
<span class="w"> </span><span class="sd">"""</span>
<span class="sd"> Return valid strings that can be passed to `torch.compile(..., backend="name")`.</span>
<span class="sd"> Args:</span>
<span class="sd"> exclude_tags(optional): A tuple of strings representing tags to exclude.</span>
<span class="sd"> """</span>
<span class="kn">import</span> <span class="nn">torch._dynamo</span>
<span class="k">return</span> <span class="n">torch</span><span class="o">.</span><span class="n">_dynamo</span><span class="o">.</span><span class="n">list_backends</span><span class="p">(</span><span class="n">exclude_tags</span><span class="p">)</span></div>
<div class="viewcode-block" id="assume_constant_result"><a class="viewcode-back" href="../../generated/torch.compiler.assume_constant_result.html#torch.compiler.assume_constant_result">[docs]</a><span class="k">def</span> <span class="nf">assume_constant_result</span><span class="p">(</span><span class="n">fn</span><span class="p">):</span>
<span class="w"> </span><span class="sd">"""</span>
<span class="sd"> This function is used to mark a function `fn` as having a constant result.</span>
<span class="sd"> This allows the compiler to optimize away your function</span>
<span class="sd"> Returns The same function `fn`</span>
<span class="sd"> Args:</span>
<span class="sd"> fn: The function to be marked as having a constant result.</span>
<span class="sd"> .. warning::</span>
<span class="sd"> `assume_constant_result` can if invalid cause safety and soundness issues, :func:`torch.compile`</span>
<span class="sd"> will not attempt to validate whether the constant assumption is true or not</span>
<span class="sd"> """</span>
<span class="kn">import</span> <span class="nn">torch._dynamo</span>
<span class="k">return</span> <span class="n">torch</span><span class="o">.</span><span class="n">_dynamo</span><span class="o">.</span><span class="n">assume_constant_result</span><span class="p">(</span><span class="n">fn</span><span class="p">)</span></div>
<div class="viewcode-block" id="disable"><a class="viewcode-back" href="../../generated/torch.compiler.disable.html#torch.compiler.disable">[docs]</a><span class="k">def</span> <span class="nf">disable</span><span class="p">(</span><span class="n">fn</span><span class="o">=</span><span class="kc">None</span><span class="p">,</span> <span class="n">recursive</span><span class="o">=</span><span class="kc">True</span><span class="p">):</span>
<span class="w"> </span><span class="sd">"""</span>
<span class="sd"> This function provides a decorator to disable compilation on a function</span>
<span class="sd"> It also provides the option of recursively disabling called functions</span>
<span class="sd"> Args:</span>
<span class="sd"> fn (optional): The function to disable</span>
<span class="sd"> recursive (optional): A boolean value indicating whether the disabling should be recursive.</span>
<span class="sd"> """</span>
<span class="kn">import</span> <span class="nn">torch._dynamo</span>
<span class="k">return</span> <span class="n">torch</span><span class="o">.</span><span class="n">_dynamo</span><span class="o">.</span><span class="n">disable</span><span class="p">(</span><span class="n">fn</span><span class="p">,</span> <span class="n">recursive</span><span class="p">)</span></div>
<div class="viewcode-block" id="set_stance"><a class="viewcode-back" href="../../generated/torch.compiler.set_stance.html#torch.compiler.set_stance">[docs]</a><span class="k">def</span> <span class="nf">set_stance</span><span class="p">(</span>
<span class="n">stance</span><span class="p">:</span> <span class="nb">str</span> <span class="o">=</span> <span class="s2">"default"</span><span class="p">,</span> <span class="o">*</span><span class="p">,</span> <span class="n">skip_guard_eval_unsafe</span><span class="o">=</span><span class="kc">False</span><span class="p">,</span> <span class="n">force_backend</span><span class="o">=</span><span class="kc">None</span>
<span class="p">):</span>
<span class="w"> </span><span class="sd">"""</span>
<span class="sd"> Set the current stance of the compiler.</span>
<span class="sd"> Can be used as a function, context manager, or decorator.</span>
<span class="sd"> Do not use this function inside a `torch.compile` region - an error will be raised otherwise.</span>
<span class="sd"> .. code-block:: python</span>
<span class="sd"> @torch.compile</span>
<span class="sd"> def foo(x):</span>
<span class="sd"> ...</span>
<span class="sd"> @torch.compiler.set_stance("force_eager")</span>
<span class="sd"> def bar():</span>
<span class="sd"> # will not be compiled</span>
<span class="sd"> foo(...)</span>
<span class="sd"> bar()</span>
<span class="sd"> with torch.compiler.set_stance("force_eager"):</span>
<span class="sd"> # will also not be compiled</span>
<span class="sd"> foo(...)</span>
<span class="sd"> torch.compiler.set_stance("force_eager")</span>
<span class="sd"> # will also not be compiled</span>
<span class="sd"> foo(...)</span>
<span class="sd"> torch.compiler.set_stance("default")</span>
<span class="sd"> # will be compiled</span>
<span class="sd"> foo(...)</span>
<span class="sd"> Args:</span>
<span class="sd"> stance: The stance to set the compiler to. Valid values are:</span>
<span class="sd"> - "default": The default stance, used for normal compilation.</span>
<span class="sd"> - "force_eager": Ignore all `torch.compile` directives.</span>
<span class="sd"> - "eager_on_recompile": Run code eagerly when a recompile is necessary.</span>
<span class="sd"> If there is cached compiled code valid for the input, it will still be used.</span>
<span class="sd"> - "fail_on_recompile": Raise an error when recompiling a function.</span>
<span class="sd"> skip_guard_eval_unsafe: A flag to run only differentiating guards.</span>
<span class="sd"> CAUTION - This flag is unsafe and should only be used if your setup</span>
<span class="sd"> meets the following conditions.</span>
<span class="sd"> torch.compile uses a guard system to support recompilations and</span>
<span class="sd"> choose which compiled artifact to run at runtime. These guards,</span>
<span class="sd"> though efficient, add some overhead, which may impact performance in</span>
<span class="sd"> scenarios where you need to optimize for minimal guard processing</span>
<span class="sd"> time. This API enables you to disable guard evaluation, assuming</span>
<span class="sd"> that you have warmed up the compiled model with a sufficient variety</span>
<span class="sd"> of inputs. This assumption means that, after the warmup phase, no</span>
<span class="sd"> further recompilations will be necessary. If this assumption fails,</span>
<span class="sd"> there is a risk of silently producing incorrect results (hence the</span>
<span class="sd"> term "unsafe" in the API name).</span>
<span class="sd"> force_backend: If `stance` is "default", this argument can be used to force `torch.compile`</span>
<span class="sd"> to use a specific backend. Otherwise, an error is raised.</span>
<span class="sd"> """</span>
<span class="kn">import</span> <span class="nn">torch._dynamo</span>
<span class="k">return</span> <span class="n">torch</span><span class="o">.</span><span class="n">_dynamo</span><span class="o">.</span><span class="n">set_stance</span><span class="p">(</span>
<span class="n">stance</span><span class="p">,</span>
<span class="n">skip_guard_eval_unsafe</span><span class="o">=</span><span class="n">skip_guard_eval_unsafe</span><span class="p">,</span>
<span class="n">force_backend</span><span class="o">=</span><span class="n">force_backend</span><span class="p">,</span>
<span class="p">)</span></div>
<span class="c1"># forbid in graph</span>
<span class="n">set_stance</span><span class="o">.</span><span class="n">_dynamo_forbidden</span> <span class="o">=</span> <span class="kc">True</span> <span class="c1"># type: ignore[attr-defined]</span>
<div class="viewcode-block" id="cudagraph_mark_step_begin"><a class="viewcode-back" href="../../generated/torch.compiler.cudagraph_mark_step_begin.html#torch.compiler.cudagraph_mark_step_begin">[docs]</a><span class="k">def</span> <span class="nf">cudagraph_mark_step_begin</span><span class="p">():</span>
<span class="w"> </span><span class="sd">"""</span>
<span class="sd"> Indicates that a new iteration of inference or training is about to begin.</span>
<span class="sd"> CUDA Graphs will free tensors of a prior iteration. A new iteration is started on each invocation of</span>
<span class="sd"> torch.compile, so long as there is not a pending backward that has not been called.</span>
<span class="sd"> If that heuristic is wrong, such as in the following example, manually mark it with this api.</span>
<span class="sd"> .. code-block:: python</span>
<span class="sd"> @torch.compile(mode="reduce-overhead")</span>
<span class="sd"> def rand_foo():</span>
<span class="sd"> return torch.rand([4], device="cuda")</span>
<span class="sd"> for _ in range(5):</span>
<span class="sd"> torch.compiler.cudagraph_mark_step_begin()</span>
<span class="sd"> rand_foo() + rand_foo()</span>
<span class="sd"> For more details, see `torch.compiler_cudagraph_trees <https://pytorch.org/docs/main/torch.compiler_cudagraph_trees.html>`__</span>
<span class="sd"> """</span>
<span class="kn">from</span> <span class="nn">torch._inductor</span> <span class="kn">import</span> <span class="n">cudagraph_trees</span>
<span class="n">cudagraph_trees</span><span class="o">.</span><span class="n">mark_step_begin</span><span class="p">()</span></div>
<span class="k">def</span> <span class="nf">wrap_numpy</span><span class="p">(</span><span class="n">fn</span><span class="p">):</span>
<span class="w"> </span><span class="sa">r</span><span class="sd">"""Decorator that turns a function from ``np.ndarray``s to ``np.ndarray``s into a function</span>
<span class="sd"> from ``torch.Tensor``s to ``torch.Tensor``s.</span>
<span class="sd"> It is designed to be used with :func:`torch.compile` with ``fullgraph=True``. It allows to</span>
<span class="sd"> compile a NumPy function as if it were a PyTorch function. This allows you to run NumPy code</span>
<span class="sd"> on CUDA or compute its gradients.</span>
<span class="sd"> .. note::</span>
<span class="sd"> This decorator does not work without :func:`torch.compile`.</span>
<span class="sd"> Example::</span>
<span class="sd"> >>> # xdoctest: +REQUIRES(env:TORCH_DOCTEST_CUDA)</span>
<span class="sd"> >>> # Compile a NumPy function as a Tensor -> Tensor function</span>
<span class="sd"> >>> @torch.compile(fullgraph=True)</span>
<span class="sd"> >>> @torch.compiler.wrap_numpy</span>
<span class="sd"> >>> def fn(a: np.ndarray):</span>
<span class="sd"> >>> return np.sum(a * a)</span>
<span class="sd"> >>> # Execute the NumPy function using Tensors on CUDA and compute the gradients</span>
<span class="sd"> >>> x = torch.arange(6, dtype=torch.float32, device="cuda", requires_grad=True)</span>
<span class="sd"> >>> out = fn(x)</span>
<span class="sd"> >>> out.backward()</span>
<span class="sd"> >>> print(x.grad)</span>
<span class="sd"> tensor([ 0., 2., 4., 6., 8., 10.], device='cuda:0')</span>
<span class="sd"> """</span>
<span class="kn">from</span> <span class="nn">torch._dynamo.external_utils</span> <span class="kn">import</span> <span class="n">wrap_numpy</span> <span class="k">as</span> <span class="n">wrap</span>
<span class="k">return</span> <span class="n">wrap</span><span class="p">(</span><span class="n">fn</span><span class="p">)</span>
<span class="n">_is_compiling_flag</span><span class="p">:</span> <span class="nb">bool</span> <span class="o">=</span> <span class="kc">False</span>
<div class="viewcode-block" id="is_compiling"><a class="viewcode-back" href="../../generated/torch.compiler.is_compiling.html#torch.compiler.is_compiling">[docs]</a><span class="k">def</span> <span class="nf">is_compiling</span><span class="p">()</span> <span class="o">-></span> <span class="nb">bool</span><span class="p">:</span>
<span class="w"> </span><span class="sd">"""</span>
<span class="sd"> Indicates whether a graph is executed/traced as part of torch.compile() or torch.export().</span>
<span class="sd"> Note that there are 2 other related flags that should deprecated eventually:</span>
<span class="sd"> * torch._dynamo.external_utils.is_compiling()</span>
<span class="sd"> * torch._utils.is_compiling()</span>
<span class="sd"> Example::</span>
<span class="sd"> >>> def forward(self, x):</span>
<span class="sd"> >>> if not torch.compiler.is_compiling():</span>
<span class="sd"> >>> pass # ...logic that is not needed in a compiled/traced graph...</span>
<span class="sd"> >>></span>
<span class="sd"> >>> # ...rest of the function...</span>
<span class="sd"> """</span>
<span class="k">if</span> <span class="n">torch</span><span class="o">.</span><span class="n">jit</span><span class="o">.</span><span class="n">is_scripting</span><span class="p">():</span>
<span class="k">return</span> <span class="kc">False</span>
<span class="k">else</span><span class="p">:</span>
<span class="k">return</span> <span class="n">_is_compiling_flag</span></div>
<div class="viewcode-block" id="is_dynamo_compiling"><a class="viewcode-back" href="../../generated/torch.compiler.is_dynamo_compiling.html#torch.compiler.is_dynamo_compiling">[docs]</a><span class="k">def</span> <span class="nf">is_dynamo_compiling</span><span class="p">()</span> <span class="o">-></span> <span class="nb">bool</span><span class="p">:</span>
<span class="w"> </span><span class="sd">"""</span>
<span class="sd"> Indicates whether a graph is traced via TorchDynamo.</span>
<span class="sd"> It's stricter than is_compiling() flag, as it would only be set to True when</span>
<span class="sd"> TorchDynamo is used.</span>
<span class="sd"> Example::</span>
<span class="sd"> >>> def forward(self, x):</span>
<span class="sd"> >>> if not torch.compiler.is_dynamo_compiling():</span>
<span class="sd"> >>> pass # ...logic that is not needed in a TorchDynamo-traced graph...</span>
<span class="sd"> >>></span>
<span class="sd"> >>> # ...rest of the function...</span>
<span class="sd"> """</span>
<span class="k">return</span> <span class="kc">False</span></div>
</pre></div>
</article>
</div>
<footer>
<hr>
<div role="contentinfo">
<p>
© Copyright 2024, PyTorch Contributors.
</p>
</div>