-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathextending.html
1940 lines (1727 loc) · 195 KB
/
extending.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 charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Extending PyTorch — PyTorch 2.7 documentation</title>
<link rel="canonical" href="https://pytorch.org/docs/stable/notes/extending.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" />
<link rel="next" title="Extending torch.func with autograd.Function" href="extending.func.html" />
<link rel="prev" title="Distributed Data Parallel" href="ddp.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-2024">
<span class="dropdown-title">Contributor Awards - 2024</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>
<a class="nav-dropdown-item" href="https://pytorch.org/executorch/stable/index.html">
<span class="dropdown-title">ExecuTorch Docs</span>
</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>
<a class="nav-dropdown-item" href="https://pytorch.org/newsletter">
<span class="dropdown-title">Newsletter</span>
<p>Stay up-to-date with the latest updates</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>
</a>
<a class="nav-dropdown-item" href="https://pytorch.org/credits">
<span class="dropdown-title">Cloud Credit Program</span>
</a>
<a class="nav-dropdown-item" href="https://pytorch.org/tac">
<span class="dropdown-title">Technical Advisory Council</span>
</a>
<a class="nav-dropdown-item" href="https://pytorch.org/staff">
<span class="dropdown-title">Staff</span>
</a>
<a class="nav-dropdown-item" href="https://pytorch.org/contact-us">
<span class="dropdown-title">Contact Us</span>
</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.7 ▼</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>
</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 class="current">
<li class="toctree-l1"><a class="reference internal" href="amp_examples.html">Automatic Mixed Precision examples</a></li>
<li class="toctree-l1"><a class="reference internal" href="autograd.html">Autograd mechanics</a></li>
<li class="toctree-l1"><a class="reference internal" href="broadcasting.html">Broadcasting semantics</a></li>
<li class="toctree-l1"><a class="reference internal" href="cpu_threading_torchscript_inference.html">CPU threading and TorchScript inference</a></li>
<li class="toctree-l1"><a class="reference internal" href="cuda.html">CUDA semantics</a></li>
<li class="toctree-l1"><a class="reference internal" href="custom_operators.html">PyTorch Custom Operators Landing Page</a></li>
<li class="toctree-l1"><a class="reference internal" href="ddp.html">Distributed Data Parallel</a></li>
<li class="toctree-l1 current"><a class="current reference internal" href="#">Extending PyTorch</a></li>
<li class="toctree-l1"><a class="reference internal" href="extending.func.html">Extending torch.func with autograd.Function</a></li>
<li class="toctree-l1"><a class="reference internal" href="faq.html">Frequently Asked Questions</a></li>
<li class="toctree-l1"><a class="reference internal" href="fsdp.html">FSDP Notes</a></li>
<li class="toctree-l1"><a class="reference internal" href="get_start_xpu.html">Getting Started on Intel GPU</a></li>
<li class="toctree-l1"><a class="reference internal" href="gradcheck.html">Gradcheck mechanics</a></li>
<li class="toctree-l1"><a class="reference internal" href="hip.html">HIP (ROCm) semantics</a></li>
<li class="toctree-l1"><a class="reference internal" href="large_scale_deployments.html">Features for large-scale deployments</a></li>
<li class="toctree-l1"><a class="reference internal" href="libtorch_stable_abi.html">LibTorch Stable ABI</a></li>
<li class="toctree-l1"><a class="reference internal" href="modules.html">Modules</a></li>
<li class="toctree-l1"><a class="reference internal" href="mps.html">MPS backend</a></li>
<li class="toctree-l1"><a class="reference internal" href="multiprocessing.html">Multiprocessing best practices</a></li>
<li class="toctree-l1"><a class="reference internal" href="numerical_accuracy.html">Numerical accuracy</a></li>
<li class="toctree-l1"><a class="reference internal" href="randomness.html">Reproducibility</a></li>
<li class="toctree-l1"><a class="reference internal" href="serialization.html">Serialization semantics</a></li>
<li class="toctree-l1"><a class="reference internal" href="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>
<li class="toctree-l1"><a class="reference external" href="https://pytorch.org/ao">torchao</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>Extending PyTorch</li>
<li class="pytorch-breadcrumbs-aside">
<a href="../_sources/notes/extending.rst.txt" rel="nofollow"><img src="../_static/images/view-page-source-icon.svg"></a>
</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">
<div class="section" id="extending-pytorch">
<h1>Extending PyTorch<a class="headerlink" href="#extending-pytorch" title="Permalink to this heading">¶</a></h1>
<p>In this note we’ll cover ways of extending <a class="reference internal" href="../nn.html#module-torch.nn" title="torch.nn"><code class="xref py py-mod docutils literal notranslate"><span class="pre">torch.nn</span></code></a>,
<a class="reference internal" href="../autograd.html#module-torch.autograd" title="torch.autograd"><code class="xref py py-mod docutils literal notranslate"><span class="pre">torch.autograd</span></code></a>, <a class="reference internal" href="../torch.html#module-torch" title="torch"><code class="xref py py-mod docutils literal notranslate"><span class="pre">torch</span></code></a>, and writing custom C++ extensions.</p>
<div class="section" id="adding-new-operators">
<h2>Adding new operators<a class="headerlink" href="#adding-new-operators" title="Permalink to this heading">¶</a></h2>
<p>PyTorch offers a large library of operators that work on Tensors (e.g. <a class="reference internal" href="../generated/torch.add.html#torch.add" title="torch.add"><code class="xref py py-func docutils literal notranslate"><span class="pre">torch.add()</span></code></a>,
<a class="reference internal" href="../generated/torch.sum.html#torch.sum" title="torch.sum"><code class="xref py py-func docutils literal notranslate"><span class="pre">torch.sum()</span></code></a>, etc). However, you may wish to bring a new custom operation to PyTorch
and have it behave like PyTorch’s built-in operators. In order to do so, you must
register the custom operation with PyTorch via the Python <a class="reference internal" href="../library.html#torch-library-docs"><span class="std std-ref">torch.library</span></a> or C++ TORCH_LIBRARY
APIs.</p>
<p>Please see <a class="reference external" href="https://pytorch.org/tutorials/advanced/custom_ops_landing_page.html">PyTorch Custom Operators Landing Page</a> for more details.</p>
</div>
<div class="section" id="extending-torch-autograd">
<span id="extending-autograd"></span><h2>Extending <a class="reference internal" href="../autograd.html#module-torch.autograd" title="torch.autograd"><code class="xref py py-mod docutils literal notranslate"><span class="pre">torch.autograd</span></code></a><a class="headerlink" href="#extending-torch-autograd" title="Permalink to this heading">¶</a></h2>
<p>Adding operations to <a class="reference internal" href="../autograd.html#module-torch.autograd" title="torch.autograd"><code class="xref py py-mod docutils literal notranslate"><span class="pre">autograd</span></code></a> requires implementing a new
<a class="reference internal" href="../autograd.html#torch.autograd.Function" title="torch.autograd.Function"><code class="xref py py-class docutils literal notranslate"><span class="pre">Function</span></code></a> subclass for each operation. Recall that Functions
are what <a class="reference internal" href="../autograd.html#module-torch.autograd" title="torch.autograd"><code class="xref py py-mod docutils literal notranslate"><span class="pre">autograd</span></code></a> uses to encode the operation history and compute
gradients.</p>
<p>The first part of this doc is focused on backward mode AD as it is the most widely used
feature. A section at the end discusses the extensions for forward mode AD.</p>
<div class="section" id="when-to-use">
<h3>When to use<a class="headerlink" href="#when-to-use" title="Permalink to this heading">¶</a></h3>
<p>In general, implement a custom function if you want to perform computations in your model
that are not differentiable or rely on non-PyTorch libraries (e.g., NumPy), but
still wish for your operation to chain with other ops and work with the autograd engine.</p>
<p>In some situations, custom functions can also be used to improve performance and
memory usage: If you implemented your forward and backward passes using a
<a class="reference external" href="https://pytorch.org/tutorials/advanced/cpp_extension.html">C++ extension</a>,
you can wrap them in <a class="reference internal" href="../autograd.html#torch.autograd.Function" title="torch.autograd.Function"><code class="xref py py-class docutils literal notranslate"><span class="pre">Function</span></code></a> to interface with the autograd
engine. If you’d like to reduce the number of buffers saved for the backward pass,
custom functions can be used to combine ops together.</p>
</div>
<div class="section" id="when-not-to-use">
<h3>When not to use<a class="headerlink" href="#when-not-to-use" title="Permalink to this heading">¶</a></h3>
<p>If you can already write your function in terms of PyTorch’s built-in ops, its
backward graph is (most likely) already able to be recorded by autograd. In this case, you do
not need to implement the backward function yourself. Consider using a plain
old Python function.</p>
<p>If you need to maintain state, i.e., trainable parameters, you should (also) use a
custom module. See the section below for more information on extending <a class="reference internal" href="../nn.html#module-torch.nn" title="torch.nn"><code class="xref py py-mod docutils literal notranslate"><span class="pre">torch.nn</span></code></a>.</p>
<p>If you’d like to alter the gradients during the backward pass or perform a side
effect, consider registering a
<a class="reference external" href="https://pytorch.org/docs/stable/generated/torch.Tensor.register_hook.html#torch.Tensor.register_hook">tensor</a> or
<a class="reference external" href="https://pytorch.org/docs/stable/notes/modules.html#module-hooks">Module</a> hook.</p>
</div>
<div class="section" id="how-to-use">
<h3>How to use<a class="headerlink" href="#how-to-use" title="Permalink to this heading">¶</a></h3>
<p>Take the following steps:
1. Subclass <a class="reference internal" href="../autograd.html#torch.autograd.Function" title="torch.autograd.Function"><code class="xref py py-class docutils literal notranslate"><span class="pre">Function</span></code></a> and implement the <a class="reference internal" href="../generated/torch.autograd.Function.forward.html#torch.autograd.Function.forward" title="torch.autograd.Function.forward"><code class="xref py py-meth docutils literal notranslate"><span class="pre">forward()</span></code></a>,
(optional) <code class="xref py py-meth docutils literal notranslate"><span class="pre">setup_context()</span></code> and
<a class="reference internal" href="../generated/torch.autograd.Function.backward.html#torch.autograd.Function.backward" title="torch.autograd.Function.backward"><code class="xref py py-meth docutils literal notranslate"><span class="pre">backward()</span></code></a> methods.
2. Call the proper methods on the <cite>ctx</cite> argument.
3. Declare whether your function supports
<a class="reference external" href="https://pytorch.org/tutorials/intermediate/custom_function_double_backward_tutorial.html">double backward</a>.
4. Validate whether your gradients are correct using gradcheck.</p>
<p><strong>Step 1:</strong> After subclassing <a class="reference internal" href="../autograd.html#torch.autograd.Function" title="torch.autograd.Function"><code class="xref py py-class docutils literal notranslate"><span class="pre">Function</span></code></a>, you’ll need to define 3 methods:</p>
<ul class="simple">
<li><p><a class="reference internal" href="../generated/torch.autograd.Function.forward.html#torch.autograd.Function.forward" title="torch.autograd.Function.forward"><code class="xref py py-meth docutils literal notranslate"><span class="pre">forward()</span></code></a> is the code that performs the operation. It can take
as many arguments as you want, with some of them being optional, if you
specify the default values. All kinds of Python objects are accepted here.
<code class="xref py py-class docutils literal notranslate"><span class="pre">Tensor</span></code> arguments that track history (i.e., with
<code class="docutils literal notranslate"><span class="pre">requires_grad=True</span></code>) will be converted to ones that don’t track history
before the call, and their use will be registered in the graph. Note that this
logic won’t traverse lists/dicts/any other data structures and will only
consider tensors that are direct arguments to the call. You can
return either a single <code class="xref py py-class docutils literal notranslate"><span class="pre">Tensor</span></code> output, or a <a class="reference external" href="https://docs.python.org/3/library/stdtypes.html#tuple" title="(in Python v3.13)"><code class="xref py py-class docutils literal notranslate"><span class="pre">tuple</span></code></a> of
tensors if there are multiple outputs. Also, please refer to the
docs of <a class="reference internal" href="../autograd.html#torch.autograd.Function" title="torch.autograd.Function"><code class="xref py py-class docutils literal notranslate"><span class="pre">Function</span></code></a> to find descriptions of useful methods that can be
called only from <a class="reference internal" href="../generated/torch.autograd.Function.forward.html#torch.autograd.Function.forward" title="torch.autograd.Function.forward"><code class="xref py py-meth docutils literal notranslate"><span class="pre">forward()</span></code></a>.</p></li>
<li><p><code class="xref py py-meth docutils literal notranslate"><span class="pre">setup_context()</span></code> (optional). One can either write a “combined” <a class="reference internal" href="../generated/torch.autograd.Function.forward.html#torch.autograd.Function.forward" title="torch.autograd.Function.forward"><code class="xref py py-meth docutils literal notranslate"><span class="pre">forward()</span></code></a> that
accepts a <code class="docutils literal notranslate"><span class="pre">ctx</span></code> object or (as of PyTorch 2.0) a separate <a class="reference internal" href="../generated/torch.autograd.Function.forward.html#torch.autograd.Function.forward" title="torch.autograd.Function.forward"><code class="xref py py-meth docutils literal notranslate"><span class="pre">forward()</span></code></a> that does
not accept <code class="docutils literal notranslate"><span class="pre">ctx</span></code> and a <code class="xref py py-meth docutils literal notranslate"><span class="pre">setup_context()</span></code> method where the <code class="docutils literal notranslate"><span class="pre">ctx</span></code> modification happens.
The <a class="reference internal" href="../generated/torch.autograd.Function.forward.html#torch.autograd.Function.forward" title="torch.autograd.Function.forward"><code class="xref py py-meth docutils literal notranslate"><span class="pre">forward()</span></code></a> should have the compute and <code class="xref py py-meth docutils literal notranslate"><span class="pre">setup_context()</span></code> should
only be responsible for the <code class="docutils literal notranslate"><span class="pre">ctx</span></code> modification (and not have any compute).
In general the separate <a class="reference internal" href="../generated/torch.autograd.Function.forward.html#torch.autograd.Function.forward" title="torch.autograd.Function.forward"><code class="xref py py-meth docutils literal notranslate"><span class="pre">forward()</span></code></a> and <code class="xref py py-meth docutils literal notranslate"><span class="pre">setup_context()</span></code> is closer to how
PyTorch native operations work and therefore more composable with various PyTorch subsystems.
See <a class="reference internal" href="#combining-forward-context"><span class="std std-ref">Combined or separate forward() and setup_context()</span></a> for more details.</p></li>
<li><p><a class="reference internal" href="../generated/torch.autograd.Function.backward.html#torch.autograd.Function.backward" title="torch.autograd.Function.backward"><code class="xref py py-meth docutils literal notranslate"><span class="pre">backward()</span></code></a> (or <code class="xref py py-meth docutils literal notranslate"><span class="pre">vjp()</span></code>) defines the gradient formula.
It will be given as many <code class="xref py py-class docutils literal notranslate"><span class="pre">Tensor</span></code> arguments as there were outputs, with each
of them representing gradient w.r.t. that output. It is important NEVER to modify
these in-place. It should return as many tensors as there
were inputs, with each of them containing the gradient w.r.t. its
corresponding input. If your inputs didn’t require gradient
(<code class="xref py py-attr docutils literal notranslate"><span class="pre">needs_input_grad</span></code> is a tuple of booleans indicating
whether each input needs gradient computation), or were non-<code class="xref py py-class docutils literal notranslate"><span class="pre">Tensor</span></code>
objects, you can return <code class="xref py py-class docutils literal notranslate"><span class="pre">python:None</span></code>. Also, if you have optional
arguments to <a class="reference internal" href="../generated/torch.autograd.Function.forward.html#torch.autograd.Function.forward" title="torch.autograd.Function.forward"><code class="xref py py-meth docutils literal notranslate"><span class="pre">forward()</span></code></a> you can return more gradients than there
were inputs, as long as they’re all <a class="reference external" href="https://docs.python.org/3/library/constants.html#None" title="(in Python v3.13)"><code class="docutils literal notranslate"><span class="pre">None</span></code></a>.</p></li>
</ul>
<p><strong>Step 2:</strong> It is your responsibility to use the functions in <code class="docutils literal notranslate"><span class="pre">ctx</span></code>
properly in order to ensure that the new <a class="reference internal" href="../autograd.html#torch.autograd.Function" title="torch.autograd.Function"><code class="xref py py-class docutils literal notranslate"><span class="pre">Function</span></code></a> works properly with
the autograd engine.</p>
<ul class="simple">
<li><p><a class="reference internal" href="../generated/torch.autograd.function.FunctionCtx.save_for_backward.html#torch.autograd.function.FunctionCtx.save_for_backward" title="torch.autograd.function.FunctionCtx.save_for_backward"><code class="xref py py-meth docutils literal notranslate"><span class="pre">save_for_backward()</span></code></a> must be
used to save any tensors to be used in the backward pass. Non-tensors should
be stored directly on <cite>ctx</cite>. If tensors that are neither input nor output
are saved for backward your <a class="reference internal" href="../autograd.html#torch.autograd.Function" title="torch.autograd.Function"><code class="xref py py-class docutils literal notranslate"><span class="pre">Function</span></code></a> may not support double backward
(see step 3).</p></li>
<li><p><a class="reference internal" href="../generated/torch.autograd.function.FunctionCtx.mark_dirty.html#torch.autograd.function.FunctionCtx.mark_dirty" title="torch.autograd.function.FunctionCtx.mark_dirty"><code class="xref py py-meth docutils literal notranslate"><span class="pre">mark_dirty()</span></code></a> must be used to
mark any input that is modified inplace by the forward function.</p></li>
<li><p><a class="reference internal" href="../generated/torch.autograd.function.FunctionCtx.mark_non_differentiable.html#torch.autograd.function.FunctionCtx.mark_non_differentiable" title="torch.autograd.function.FunctionCtx.mark_non_differentiable"><code class="xref py py-meth docutils literal notranslate"><span class="pre">mark_non_differentiable()</span></code></a> must
be used to tell the engine if an output is not differentiable. By
default all output tensors that are of differentiable type will be set
to require gradient. Tensors of non-differentiable type (i.e., integral types)
are never marked as requiring gradients.</p></li>
<li><p><a class="reference internal" href="../generated/torch.autograd.function.FunctionCtx.set_materialize_grads.html#torch.autograd.function.FunctionCtx.set_materialize_grads" title="torch.autograd.function.FunctionCtx.set_materialize_grads"><code class="xref py py-meth docutils literal notranslate"><span class="pre">set_materialize_grads()</span></code></a> can be
used to tell the autograd engine to optimize gradient computations in the cases where
the output does not depend on the input by not materializing grad tensors given to backward
function. That is, if set to False, None object in Python or “undefined tensor” (tensor x for
which x.defined() is False) in C++ will not be converted to a tensor filled with zeros prior
to calling backward, and so your code will need to handle such objects as if they were
tensors filled with zeros. The default value of this setting is True.</p></li>
</ul>
<p><strong>Step 3:</strong> If your <a class="reference internal" href="../autograd.html#torch.autograd.Function" title="torch.autograd.Function"><code class="xref py py-class docutils literal notranslate"><span class="pre">Function</span></code></a> does not support double backward
you should explicitly declare this by decorating backward with the
<a class="reference internal" href="../generated/torch.autograd.function.once_differentiable.html#torch.autograd.function.once_differentiable" title="torch.autograd.function.once_differentiable"><code class="xref py py-func docutils literal notranslate"><span class="pre">once_differentiable()</span></code></a>. With this decorator, attempts to
perform double backward through your function will produce an error.
See our double backward tutorial for more information on double backward.</p>
<p><strong>Step 4:</strong> It is recommended that you use <a class="reference internal" href="../autograd.html#module-torch.autograd.gradcheck" title="torch.autograd.gradcheck"><code class="xref py py-func docutils literal notranslate"><span class="pre">torch.autograd.gradcheck()</span></code></a>
to check whether your backward function correctly computes gradients of the
forward by computing the Jacobian matrix using your backward function and
comparing the value element-wise with the Jacobian computed numerically using
finite-differencing.</p>
</div>
<div class="section" id="example">
<h3>Example<a class="headerlink" href="#example" title="Permalink to this heading">¶</a></h3>
<p>Below you can find code for a <code class="docutils literal notranslate"><span class="pre">Linear</span></code> function, with
additional comments:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="c1"># Inherit from Function</span>
<span class="k">class</span> <span class="nc">LinearFunction</span><span class="p">(</span><span class="n">Function</span><span class="p">):</span>
<span class="c1"># Note that forward, setup_context, and backward are @staticmethods</span>
<span class="nd">@staticmethod</span>
<span class="k">def</span> <span class="nf">forward</span><span class="p">(</span><span class="nb">input</span><span class="p">,</span> <span class="n">weight</span><span class="p">,</span> <span class="n">bias</span><span class="p">):</span>
<span class="n">output</span> <span class="o">=</span> <span class="nb">input</span><span class="o">.</span><span class="n">mm</span><span class="p">(</span><span class="n">weight</span><span class="o">.</span><span class="n">t</span><span class="p">())</span>
<span class="k">if</span> <span class="n">bias</span> <span class="ow">is</span> <span class="ow">not</span> <span class="kc">None</span><span class="p">:</span>
<span class="n">output</span> <span class="o">+=</span> <span class="n">bias</span><span class="o">.</span><span class="n">unsqueeze</span><span class="p">(</span><span class="mi">0</span><span class="p">)</span><span class="o">.</span><span class="n">expand_as</span><span class="p">(</span><span class="n">output</span><span class="p">)</span>
<span class="k">return</span> <span class="n">output</span>
<span class="nd">@staticmethod</span>
<span class="c1"># inputs is a Tuple of all of the inputs passed to forward.</span>
<span class="c1"># output is the output of the forward().</span>
<span class="k">def</span> <span class="nf">setup_context</span><span class="p">(</span><span class="n">ctx</span><span class="p">,</span> <span class="n">inputs</span><span class="p">,</span> <span class="n">output</span><span class="p">):</span>
<span class="nb">input</span><span class="p">,</span> <span class="n">weight</span><span class="p">,</span> <span class="n">bias</span> <span class="o">=</span> <span class="n">inputs</span>
<span class="n">ctx</span><span class="o">.</span><span class="n">save_for_backward</span><span class="p">(</span><span class="nb">input</span><span class="p">,</span> <span class="n">weight</span><span class="p">,</span> <span class="n">bias</span><span class="p">)</span>
<span class="c1"># This function has only a single output, so it gets only one gradient</span>
<span class="nd">@staticmethod</span>
<span class="k">def</span> <span class="nf">backward</span><span class="p">(</span><span class="n">ctx</span><span class="p">,</span> <span class="n">grad_output</span><span class="p">):</span>
<span class="c1"># This is a pattern that is very convenient - at the top of backward</span>
<span class="c1"># unpack saved_tensors and initialize all gradients w.r.t. inputs to</span>
<span class="c1"># None. Thanks to the fact that additional trailing Nones are</span>
<span class="c1"># ignored, the return statement is simple even when the function has</span>
<span class="c1"># optional inputs.</span>
<span class="nb">input</span><span class="p">,</span> <span class="n">weight</span><span class="p">,</span> <span class="n">bias</span> <span class="o">=</span> <span class="n">ctx</span><span class="o">.</span><span class="n">saved_tensors</span>
<span class="n">grad_input</span> <span class="o">=</span> <span class="n">grad_weight</span> <span class="o">=</span> <span class="n">grad_bias</span> <span class="o">=</span> <span class="kc">None</span>
<span class="c1"># These needs_input_grad checks are optional and there only to</span>
<span class="c1"># improve efficiency. If you want to make your code simpler, you can</span>
<span class="c1"># skip them. Returning gradients for inputs that don't require it is</span>
<span class="c1"># not an error.</span>
<span class="k">if</span> <span class="n">ctx</span><span class="o">.</span><span class="n">needs_input_grad</span><span class="p">[</span><span class="mi">0</span><span class="p">]:</span>
<span class="n">grad_input</span> <span class="o">=</span> <span class="n">grad_output</span><span class="o">.</span><span class="n">mm</span><span class="p">(</span><span class="n">weight</span><span class="p">)</span>
<span class="k">if</span> <span class="n">ctx</span><span class="o">.</span><span class="n">needs_input_grad</span><span class="p">[</span><span class="mi">1</span><span class="p">]:</span>
<span class="n">grad_weight</span> <span class="o">=</span> <span class="n">grad_output</span><span class="o">.</span><span class="n">t</span><span class="p">()</span><span class="o">.</span><span class="n">mm</span><span class="p">(</span><span class="nb">input</span><span class="p">)</span>
<span class="k">if</span> <span class="n">bias</span> <span class="ow">is</span> <span class="ow">not</span> <span class="kc">None</span> <span class="ow">and</span> <span class="n">ctx</span><span class="o">.</span><span class="n">needs_input_grad</span><span class="p">[</span><span class="mi">2</span><span class="p">]:</span>
<span class="n">grad_bias</span> <span class="o">=</span> <span class="n">grad_output</span><span class="o">.</span><span class="n">sum</span><span class="p">(</span><span class="mi">0</span><span class="p">)</span>
<span class="k">return</span> <span class="n">grad_input</span><span class="p">,</span> <span class="n">grad_weight</span><span class="p">,</span> <span class="n">grad_bias</span>
</pre></div>
</div>
<p>Now, to make it easier to use these custom ops, we recommend either aliasing
them or wrapping them in a function. Wrapping in a function lets us support
default arguments and keyword arguments:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="c1"># Option 1: alias</span>
<span class="n">linear</span> <span class="o">=</span> <span class="n">LinearFunction</span><span class="o">.</span><span class="n">apply</span>
<span class="c1"># Option 2: wrap in a function, to support default args and keyword args.</span>
<span class="k">def</span> <span class="nf">linear</span><span class="p">(</span><span class="nb">input</span><span class="p">,</span> <span class="n">weight</span><span class="p">,</span> <span class="n">bias</span><span class="o">=</span><span class="kc">None</span><span class="p">):</span>
<span class="k">return</span> <span class="n">LinearFunction</span><span class="o">.</span><span class="n">apply</span><span class="p">(</span><span class="nb">input</span><span class="p">,</span> <span class="n">weight</span><span class="p">,</span> <span class="n">bias</span><span class="p">)</span>
</pre></div>
</div>
<p>Here, we give an additional example of a function that is parametrized by
non-Tensor arguments:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="k">class</span> <span class="nc">MulConstant</span><span class="p">(</span><span class="n">Function</span><span class="p">):</span>
<span class="nd">@staticmethod</span>
<span class="k">def</span> <span class="nf">forward</span><span class="p">(</span><span class="n">tensor</span><span class="p">,</span> <span class="n">constant</span><span class="p">):</span>
<span class="k">return</span> <span class="n">tensor</span> <span class="o">*</span> <span class="n">constant</span>
<span class="nd">@staticmethod</span>
<span class="k">def</span> <span class="nf">setup_context</span><span class="p">(</span><span class="n">ctx</span><span class="p">,</span> <span class="n">inputs</span><span class="p">,</span> <span class="n">output</span><span class="p">):</span>
<span class="c1"># ctx is a context object that can be used to stash information</span>
<span class="c1"># for backward computation</span>
<span class="n">tensor</span><span class="p">,</span> <span class="n">constant</span> <span class="o">=</span> <span class="n">inputs</span>
<span class="n">ctx</span><span class="o">.</span><span class="n">constant</span> <span class="o">=</span> <span class="n">constant</span>
<span class="nd">@staticmethod</span>
<span class="k">def</span> <span class="nf">backward</span><span class="p">(</span><span class="n">ctx</span><span class="p">,</span> <span class="n">grad_output</span><span class="p">):</span>
<span class="c1"># We return as many input gradients as there were arguments.</span>
<span class="c1"># Gradients of non-Tensor arguments to forward must be None.</span>
<span class="k">return</span> <span class="n">grad_output</span> <span class="o">*</span> <span class="n">ctx</span><span class="o">.</span><span class="n">constant</span><span class="p">,</span> <span class="kc">None</span>
</pre></div>
</div>
<p>And here, we optimize the above example by calling set_materialize_grads(False):</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="k">class</span> <span class="nc">MulConstant</span><span class="p">(</span><span class="n">Function</span><span class="p">):</span>
<span class="nd">@staticmethod</span>
<span class="k">def</span> <span class="nf">forward</span><span class="p">(</span><span class="n">tensor</span><span class="p">,</span> <span class="n">constant</span><span class="p">):</span>
<span class="k">return</span> <span class="n">tensor</span> <span class="o">*</span> <span class="n">constant</span>
<span class="nd">@staticmethod</span>
<span class="k">def</span> <span class="nf">setup_context</span><span class="p">(</span><span class="n">ctx</span><span class="p">,</span> <span class="n">inputs</span><span class="p">,</span> <span class="n">output</span><span class="p">):</span>
<span class="n">tensor</span><span class="p">,</span> <span class="n">constant</span> <span class="o">=</span> <span class="n">inputs</span>
<span class="n">ctx</span><span class="o">.</span><span class="n">set_materialize_grads</span><span class="p">(</span><span class="kc">False</span><span class="p">)</span>
<span class="n">ctx</span><span class="o">.</span><span class="n">constant</span> <span class="o">=</span> <span class="n">constant</span>
<span class="nd">@staticmethod</span>
<span class="k">def</span> <span class="nf">backward</span><span class="p">(</span><span class="n">ctx</span><span class="p">,</span> <span class="n">grad_output</span><span class="p">):</span>
<span class="c1"># Here we must handle None grad_output tensor. In this case we</span>
<span class="c1"># can skip unnecessary computations and just return None.</span>
<span class="k">if</span> <span class="n">grad_output</span> <span class="ow">is</span> <span class="kc">None</span><span class="p">:</span>
<span class="k">return</span> <span class="kc">None</span><span class="p">,</span> <span class="kc">None</span>
<span class="c1"># We return as many input gradients as there were arguments.</span>
<span class="c1"># Gradients of non-Tensor arguments to forward must be None.</span>
<span class="k">return</span> <span class="n">grad_output</span> <span class="o">*</span> <span class="n">ctx</span><span class="o">.</span><span class="n">constant</span><span class="p">,</span> <span class="kc">None</span>
</pre></div>
</div>
<p>If you need any “intermediate” Tensors computed in <a class="reference internal" href="../generated/torch.autograd.Function.forward.html#torch.autograd.Function.forward" title="torch.autograd.Function.forward"><code class="xref py py-meth docutils literal notranslate"><span class="pre">forward()</span></code></a> to be saved,
either they must be returned as outputs, or combine <code class="docutils literal notranslate"><span class="pre">forward</span></code> and <code class="xref py py-meth docutils literal notranslate"><span class="pre">setup_context()</span></code>
(see <a class="reference internal" href="#combining-forward-context"><span class="std std-ref">Combined or separate forward() and setup_context()</span></a>).
Note that this means if you want gradients to flow through those intermediate values, you
need to define the gradient formula for them (see also
<a class="reference external" href="https://pytorch.org/tutorials/intermediate/custom_function_double_backward_tutorial.html">the double backward tutorial</a>
):</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="k">class</span> <span class="nc">MyCube</span><span class="p">(</span><span class="n">torch</span><span class="o">.</span><span class="n">autograd</span><span class="o">.</span><span class="n">Function</span><span class="p">):</span>
<span class="nd">@staticmethod</span>
<span class="k">def</span> <span class="nf">forward</span><span class="p">(</span><span class="n">x</span><span class="p">):</span>
<span class="c1"># We wish to save dx for backward. In order to do so, it must</span>
<span class="c1"># be returned as an output.</span>
<span class="n">dx</span> <span class="o">=</span> <span class="mi">3</span> <span class="o">*</span> <span class="n">x</span> <span class="o">**</span> <span class="mi">2</span>
<span class="n">result</span> <span class="o">=</span> <span class="n">x</span> <span class="o">**</span> <span class="mi">3</span>
<span class="k">return</span> <span class="n">result</span><span class="p">,</span> <span class="n">dx</span>
<span class="nd">@staticmethod</span>
<span class="k">def</span> <span class="nf">setup_context</span><span class="p">(</span><span class="n">ctx</span><span class="p">,</span> <span class="n">inputs</span><span class="p">,</span> <span class="n">output</span><span class="p">):</span>
<span class="n">x</span><span class="p">,</span> <span class="o">=</span> <span class="n">inputs</span>
<span class="n">result</span><span class="p">,</span> <span class="n">dx</span> <span class="o">=</span> <span class="n">output</span>
<span class="n">ctx</span><span class="o">.</span><span class="n">save_for_backward</span><span class="p">(</span><span class="n">x</span><span class="p">,</span> <span class="n">dx</span><span class="p">)</span>
<span class="nd">@staticmethod</span>
<span class="k">def</span> <span class="nf">backward</span><span class="p">(</span><span class="n">ctx</span><span class="p">,</span> <span class="n">grad_output</span><span class="p">,</span> <span class="n">grad_dx</span><span class="p">):</span>
<span class="n">x</span><span class="p">,</span> <span class="n">dx</span> <span class="o">=</span> <span class="n">ctx</span><span class="o">.</span><span class="n">saved_tensors</span>
<span class="c1"># In order for the autograd.Function to work with higher-order</span>
<span class="c1"># gradients, we must add the gradient contribution of `dx`,</span>
<span class="c1"># which is grad_dx * 6 * x.</span>
<span class="n">result</span> <span class="o">=</span> <span class="n">grad_output</span> <span class="o">*</span> <span class="n">dx</span> <span class="o">+</span> <span class="n">grad_dx</span> <span class="o">*</span> <span class="mi">6</span> <span class="o">*</span> <span class="n">x</span>
<span class="k">return</span> <span class="n">result</span>
<span class="c1"># Wrap MyCube in a function so that it is clearer what the output is</span>
<span class="k">def</span> <span class="nf">my_cube</span><span class="p">(</span><span class="n">x</span><span class="p">):</span>
<span class="n">result</span><span class="p">,</span> <span class="n">dx</span> <span class="o">=</span> <span class="n">MyCube</span><span class="o">.</span><span class="n">apply</span><span class="p">(</span><span class="n">x</span><span class="p">)</span>
<span class="k">return</span> <span class="n">result</span>
</pre></div>
</div>
<div class="admonition note">
<p class="admonition-title">Note</p>
<p>Inputs to <code class="docutils literal notranslate"><span class="pre">backward</span></code>, i.e., <code class="xref py py-attr docutils literal notranslate"><span class="pre">grad_output</span></code>, can also be tensors that
track history. So if <code class="docutils literal notranslate"><span class="pre">backward</span></code> is implemented with differentiable
operations, (e.g., invocation of another custom
<a class="reference internal" href="../autograd.html#torch.autograd.Function" title="torch.autograd.Function"><code class="xref py py-class docutils literal notranslate"><span class="pre">Function</span></code></a>), higher order derivatives will work.
In this case, the tensors saved with <code class="docutils literal notranslate"><span class="pre">save_for_backward</span></code> can also be used
in the backward and have gradients flowing back but tensors saved in the <code class="docutils literal notranslate"><span class="pre">ctx</span></code>
won’t have gradients flowing back for them.
If you need gradients to flow back for a Tensor saved in the <code class="docutils literal notranslate"><span class="pre">ctx</span></code>, you should
make it an output of the custom <code class="docutils literal notranslate"><span class="pre">Function</span></code> and save it with <code class="docutils literal notranslate"><span class="pre">save_for_backward</span></code>.</p>
</div>
<p>You probably want to check if the backward method you implemented actually
computes the derivatives of your function. It is possible by comparing with
numerical approximations using small finite differences:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="kn">from</span> <span class="nn">torch.autograd</span> <span class="kn">import</span> <span class="n">gradcheck</span>
<span class="c1"># gradcheck takes a tuple of tensors as input, check if your gradient</span>
<span class="c1"># evaluated with these tensors are close enough to numerical</span>
<span class="c1"># approximations and returns True if they all verify this condition.</span>
<span class="nb">input</span> <span class="o">=</span> <span class="p">(</span><span class="n">torch</span><span class="o">.</span><span class="n">randn</span><span class="p">(</span><span class="mi">20</span><span class="p">,</span><span class="mi">20</span><span class="p">,</span><span class="n">dtype</span><span class="o">=</span><span class="n">torch</span><span class="o">.</span><span class="n">double</span><span class="p">,</span><span class="n">requires_grad</span><span class="o">=</span><span class="kc">True</span><span class="p">),</span> <span class="n">torch</span><span class="o">.</span><span class="n">randn</span><span class="p">(</span><span class="mi">30</span><span class="p">,</span><span class="mi">20</span><span class="p">,</span><span class="n">dtype</span><span class="o">=</span><span class="n">torch</span><span class="o">.</span><span class="n">double</span><span class="p">,</span><span class="n">requires_grad</span><span class="o">=</span><span class="kc">True</span><span class="p">))</span>
<span class="n">test</span> <span class="o">=</span> <span class="n">gradcheck</span><span class="p">(</span><span class="n">linear</span><span class="p">,</span> <span class="nb">input</span><span class="p">,</span> <span class="n">eps</span><span class="o">=</span><span class="mf">1e-6</span><span class="p">,</span> <span class="n">atol</span><span class="o">=</span><span class="mf">1e-4</span><span class="p">)</span>
<span class="nb">print</span><span class="p">(</span><span class="n">test</span><span class="p">)</span>
</pre></div>
</div>
<p>See <a class="reference internal" href="../autograd.html#grad-check"><span class="std std-ref">Numerical gradient checking</span></a> for more details on finite-difference gradient comparisons.
If your function is used in higher order derivatives (differentiating the backward pass) you
can use the <code class="docutils literal notranslate"><span class="pre">gradgradcheck</span></code> function from the same package to check higher order derivatives.</p>
</div>
<div class="section" id="combined-or-separate-forward-and-setup-context">
<span id="combining-forward-context"></span><h3>Combined or separate <a class="reference internal" href="../generated/torch.autograd.Function.forward.html#torch.autograd.Function.forward" title="torch.autograd.Function.forward"><code class="xref py py-meth docutils literal notranslate"><span class="pre">forward()</span></code></a> and <code class="xref py py-meth docutils literal notranslate"><span class="pre">setup_context()</span></code><a class="headerlink" href="#combined-or-separate-forward-and-setup-context" title="Permalink to this heading">¶</a></h3>
<p>There are two main ways to define <a class="reference internal" href="../autograd.html#torch.autograd.Function" title="torch.autograd.Function"><code class="xref py py-class docutils literal notranslate"><span class="pre">Function</span></code></a>. Either:</p>
<ul class="simple">
<li><p>define a <a class="reference internal" href="../generated/torch.autograd.Function.forward.html#torch.autograd.Function.forward" title="torch.autograd.Function.forward"><code class="xref py py-meth docutils literal notranslate"><span class="pre">forward()</span></code></a> that combines the forward compute logic with <code class="xref py py-meth docutils literal notranslate"><span class="pre">setup_context()</span></code></p></li>
<li><p>(as of PyTorch 2.0) define a separate <a class="reference internal" href="../generated/torch.autograd.Function.forward.html#torch.autograd.Function.forward" title="torch.autograd.Function.forward"><code class="xref py py-meth docutils literal notranslate"><span class="pre">forward()</span></code></a> and <code class="xref py py-meth docutils literal notranslate"><span class="pre">setup_context()</span></code></p></li>
</ul>
<p>We recommend the second option (separate <a class="reference internal" href="../generated/torch.autograd.Function.forward.html#torch.autograd.Function.forward" title="torch.autograd.Function.forward"><code class="xref py py-meth docutils literal notranslate"><span class="pre">forward()</span></code></a> and <code class="xref py py-meth docutils literal notranslate"><span class="pre">setup_context()</span></code>)
because that is closer to how PyTorch native operations are implemented and it composes
with <a class="reference internal" href="../func.api.html#module-torch.func" title="torch.func"><code class="xref py py-mod docutils literal notranslate"><span class="pre">torch.func</span></code></a> transforms. However, we plan to support both approaches going forward;
combining <a class="reference internal" href="../generated/torch.autograd.Function.forward.html#torch.autograd.Function.forward" title="torch.autograd.Function.forward"><code class="xref py py-meth docutils literal notranslate"><span class="pre">forward()</span></code></a> with <code class="xref py py-meth docutils literal notranslate"><span class="pre">setup_context()</span></code>: leads to more flexibility since
you are able to save intermediates without returning them as output.</p>
<p>Please see the previous section for how to define <a class="reference internal" href="../autograd.html#torch.autograd.Function" title="torch.autograd.Function"><code class="xref py py-class docutils literal notranslate"><span class="pre">Function</span></code></a> with separate
<a class="reference internal" href="../generated/torch.autograd.Function.forward.html#torch.autograd.Function.forward" title="torch.autograd.Function.forward"><code class="xref py py-meth docutils literal notranslate"><span class="pre">forward()</span></code></a> and <code class="xref py py-meth docutils literal notranslate"><span class="pre">setup_context()</span></code>.</p>
<p>Here is an example of how to define a <a class="reference internal" href="../autograd.html#torch.autograd.Function" title="torch.autograd.Function"><code class="xref py py-class docutils literal notranslate"><span class="pre">Function</span></code></a> with combined <a class="reference internal" href="../generated/torch.autograd.Function.forward.html#torch.autograd.Function.forward" title="torch.autograd.Function.forward"><code class="xref py py-meth docutils literal notranslate"><span class="pre">forward()</span></code></a> and
<code class="xref py py-meth docutils literal notranslate"><span class="pre">setup_context()</span></code>:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="k">class</span> <span class="nc">LinearFunction</span><span class="p">(</span><span class="n">Function</span><span class="p">):</span>
<span class="nd">@staticmethod</span>
<span class="c1"># ctx is the first argument to forward</span>
<span class="k">def</span> <span class="nf">forward</span><span class="p">(</span><span class="n">ctx</span><span class="p">,</span> <span class="nb">input</span><span class="p">,</span> <span class="n">weight</span><span class="p">,</span> <span class="n">bias</span><span class="o">=</span><span class="kc">None</span><span class="p">):</span>
<span class="c1"># The forward pass can use ctx.</span>
<span class="n">ctx</span><span class="o">.</span><span class="n">save_for_backward</span><span class="p">(</span><span class="nb">input</span><span class="p">,</span> <span class="n">weight</span><span class="p">,</span> <span class="n">bias</span><span class="p">)</span>
<span class="n">output</span> <span class="o">=</span> <span class="nb">input</span><span class="o">.</span><span class="n">mm</span><span class="p">(</span><span class="n">weight</span><span class="o">.</span><span class="n">t</span><span class="p">())</span>
<span class="k">if</span> <span class="n">bias</span> <span class="ow">is</span> <span class="ow">not</span> <span class="kc">None</span><span class="p">:</span>
<span class="n">output</span> <span class="o">+=</span> <span class="n">bias</span><span class="o">.</span><span class="n">unsqueeze</span><span class="p">(</span><span class="mi">0</span><span class="p">)</span><span class="o">.</span><span class="n">expand_as</span><span class="p">(</span><span class="n">output</span><span class="p">)</span>
<span class="k">return</span> <span class="n">output</span>
<span class="nd">@staticmethod</span>
<span class="k">def</span> <span class="nf">backward</span><span class="p">(</span><span class="n">ctx</span><span class="p">,</span> <span class="n">grad_output</span><span class="p">):</span>
<span class="nb">input</span><span class="p">,</span> <span class="n">weight</span><span class="p">,</span> <span class="n">bias</span> <span class="o">=</span> <span class="n">ctx</span><span class="o">.</span><span class="n">saved_tensors</span>
<span class="n">grad_input</span> <span class="o">=</span> <span class="n">grad_weight</span> <span class="o">=</span> <span class="n">grad_bias</span> <span class="o">=</span> <span class="kc">None</span>
<span class="k">if</span> <span class="n">ctx</span><span class="o">.</span><span class="n">needs_input_grad</span><span class="p">[</span><span class="mi">0</span><span class="p">]:</span>
<span class="n">grad_input</span> <span class="o">=</span> <span class="n">grad_output</span><span class="o">.</span><span class="n">mm</span><span class="p">(</span><span class="n">weight</span><span class="p">)</span>
<span class="k">if</span> <span class="n">ctx</span><span class="o">.</span><span class="n">needs_input_grad</span><span class="p">[</span><span class="mi">1</span><span class="p">]:</span>
<span class="n">grad_weight</span> <span class="o">=</span> <span class="n">grad_output</span><span class="o">.</span><span class="n">t</span><span class="p">()</span><span class="o">.</span><span class="n">mm</span><span class="p">(</span><span class="nb">input</span><span class="p">)</span>
<span class="k">if</span> <span class="n">bias</span> <span class="ow">is</span> <span class="ow">not</span> <span class="kc">None</span> <span class="ow">and</span> <span class="n">ctx</span><span class="o">.</span><span class="n">needs_input_grad</span><span class="p">[</span><span class="mi">2</span><span class="p">]:</span>
<span class="n">grad_bias</span> <span class="o">=</span> <span class="n">grad_output</span><span class="o">.</span><span class="n">sum</span><span class="p">(</span><span class="mi">0</span><span class="p">)</span>
<span class="k">return</span> <span class="n">grad_input</span><span class="p">,</span> <span class="n">grad_weight</span><span class="p">,</span> <span class="n">grad_bias</span>
</pre></div>
</div>
</div>
<div class="section" id="forward-mode-ad">
<span id="forward-ad-autograd-function"></span><h3>Forward mode AD<a class="headerlink" href="#forward-mode-ad" title="Permalink to this heading">¶</a></h3>
<p>Overriding the forward mode AD formula has a very similar API with some different subtleties.
You can implement the <a class="reference internal" href="../generated/torch.autograd.Function.jvp.html#torch.autograd.Function.jvp" title="torch.autograd.Function.jvp"><code class="xref py py-meth docutils literal notranslate"><span class="pre">jvp()</span></code></a> function.</p>
<p>It will be given as many <code class="xref py py-class docutils literal notranslate"><span class="pre">Tensor</span></code> arguments as there were inputs, with each
of them representing gradient w.r.t. that input. It should return as many tensors as there
were outputs, with each of them containing the gradient w.r.t. its corresponding output.
The <a class="reference internal" href="../generated/torch.autograd.Function.jvp.html#torch.autograd.Function.jvp" title="torch.autograd.Function.jvp"><code class="xref py py-meth docutils literal notranslate"><span class="pre">jvp()</span></code></a> will be called just after the <a class="reference internal" href="../generated/torch.autograd.Function.forward.html#torch.autograd.Function.forward" title="torch.autograd.Function.forward"><code class="xref py py-meth docutils literal notranslate"><span class="pre">forward()</span></code></a>
method, before the <code class="xref py py-meth docutils literal notranslate"><span class="pre">apply()</span></code> returns.</p>
<p><a class="reference internal" href="../generated/torch.autograd.Function.jvp.html#torch.autograd.Function.jvp" title="torch.autograd.Function.jvp"><code class="xref py py-meth docutils literal notranslate"><span class="pre">jvp()</span></code></a> has a few subtle differences with the <a class="reference internal" href="../generated/torch.autograd.Function.backward.html#torch.autograd.Function.backward" title="torch.autograd.Function.backward"><code class="xref py py-meth docutils literal notranslate"><span class="pre">backward()</span></code></a> function:</p>
<ul class="simple">
<li><p>You can use the <cite>ctx</cite> to pass any data from the <a class="reference internal" href="../generated/torch.autograd.Function.forward.html#torch.autograd.Function.forward" title="torch.autograd.Function.forward"><code class="xref py py-meth docutils literal notranslate"><span class="pre">forward()</span></code></a> to the <a class="reference internal" href="../generated/torch.autograd.Function.jvp.html#torch.autograd.Function.jvp" title="torch.autograd.Function.jvp"><code class="xref py py-meth docutils literal notranslate"><span class="pre">jvp()</span></code></a> function.
If that state will not be needed for the <a class="reference internal" href="../generated/torch.autograd.Function.backward.html#torch.autograd.Function.backward" title="torch.autograd.Function.backward"><code class="xref py py-meth docutils literal notranslate"><span class="pre">backward()</span></code></a>,
you can explicitly free it by doing <code class="docutils literal notranslate"><span class="pre">del</span> <span class="pre">ctx.foo</span></code> at the end of the <a class="reference internal" href="../generated/torch.autograd.Function.jvp.html#torch.autograd.Function.jvp" title="torch.autograd.Function.jvp"><code class="xref py py-meth docutils literal notranslate"><span class="pre">jvp()</span></code></a> function.</p></li>
<li><p>The implementation of <a class="reference internal" href="../generated/torch.autograd.Function.jvp.html#torch.autograd.Function.jvp" title="torch.autograd.Function.jvp"><code class="xref py py-meth docutils literal notranslate"><span class="pre">jvp()</span></code></a> must be backward differentiable or explicitly check that
none of the given forward mode gradient has <code class="docutils literal notranslate"><span class="pre">requires_grad</span></code> set.</p></li>
<li><p>The <a class="reference internal" href="../generated/torch.autograd.Function.jvp.html#torch.autograd.Function.jvp" title="torch.autograd.Function.jvp"><code class="xref py py-meth docutils literal notranslate"><span class="pre">jvp()</span></code></a> function must match the view/inplace behavior of <a class="reference internal" href="../generated/torch.autograd.Function.forward.html#torch.autograd.Function.forward" title="torch.autograd.Function.forward"><code class="xref py py-meth docutils literal notranslate"><span class="pre">forward()</span></code></a>.
For example, if the <code class="docutils literal notranslate"><span class="pre">i</span></code> th input is modified inplace, then the <code class="docutils literal notranslate"><span class="pre">i</span></code> th gradient must be updated inplace.
Similarly, if the <code class="docutils literal notranslate"><span class="pre">j</span></code> th output is a view of the <code class="docutils literal notranslate"><span class="pre">k</span></code> th input. Then the returned <code class="docutils literal notranslate"><span class="pre">j</span></code> th output gradient must be
a view of the given <code class="docutils literal notranslate"><span class="pre">k</span></code> th input gradient.</p></li>
<li><p>Because the user cannot specify which gradient needs to be computed, the <a class="reference internal" href="../generated/torch.autograd.Function.jvp.html#torch.autograd.Function.jvp" title="torch.autograd.Function.jvp"><code class="xref py py-meth docutils literal notranslate"><span class="pre">jvp()</span></code></a> function should
always compute gradients for all the outputs.</p></li>
<li><p>The forward mode gradients do respect the flag set by <a class="reference internal" href="../generated/torch.autograd.function.FunctionCtx.set_materialize_grads.html#torch.autograd.function.FunctionCtx.set_materialize_grads" title="torch.autograd.function.FunctionCtx.set_materialize_grads"><code class="xref py py-meth docutils literal notranslate"><span class="pre">set_materialize_grads()</span></code></a>
and you can get <cite>None</cite> input gradients when this is disabled.</p></li>
</ul>
</div>
<div class="section" id="torch-func-transforms-and-or-torch-vmap">
<h3><a class="reference internal" href="../func.api.html#module-torch.func" title="torch.func"><code class="xref py py-mod docutils literal notranslate"><span class="pre">torch.func</span></code></a> transforms and/or <a class="reference internal" href="../generated/torch.vmap.html#torch.vmap" title="torch.vmap"><code class="xref py py-func docutils literal notranslate"><span class="pre">torch.vmap()</span></code></a><a class="headerlink" href="#torch-func-transforms-and-or-torch-vmap" title="Permalink to this heading">¶</a></h3>
<p>Please see <a class="reference internal" href="extending.func.html#func-autograd-function"><span class="std std-ref">Extending torch.func with autograd.Function</span></a> for details.</p>
</div>
</div>
<div class="section" id="extending-torch-nn">
<h2>Extending <a class="reference internal" href="../nn.html#module-torch.nn" title="torch.nn"><code class="xref py py-mod docutils literal notranslate"><span class="pre">torch.nn</span></code></a><a class="headerlink" href="#extending-torch-nn" title="Permalink to this heading">¶</a></h2>
<p><a class="reference internal" href="../nn.html#module-torch.nn" title="torch.nn"><code class="xref py py-mod docutils literal notranslate"><span class="pre">nn</span></code></a> exports two kinds of interfaces - modules and their functional
versions. You can extend it in both ways, but we recommend using modules for
all kinds of layers, that hold any parameters or buffers, and recommend using
a functional form parameter-less operations like activation functions, pooling,
etc.</p>
<p>Adding a functional version of an operation is already fully covered in the
section above.</p>
<div class="section" id="adding-a-module">
<h3>Adding a <a class="reference internal" href="../generated/torch.nn.Module.html#torch.nn.Module" title="torch.nn.Module"><code class="xref py py-class docutils literal notranslate"><span class="pre">Module</span></code></a><a class="headerlink" href="#adding-a-module" title="Permalink to this heading">¶</a></h3>
<p>Since <a class="reference internal" href="../nn.html#module-torch.nn" title="torch.nn"><code class="xref py py-mod docutils literal notranslate"><span class="pre">nn</span></code></a> heavily utilizes <a class="reference internal" href="../autograd.html#module-torch.autograd" title="torch.autograd"><code class="xref py py-mod docutils literal notranslate"><span class="pre">autograd</span></code></a>, adding a new
<a class="reference internal" href="../generated/torch.nn.Module.html#torch.nn.Module" title="torch.nn.Module"><code class="xref py py-class docutils literal notranslate"><span class="pre">Module</span></code></a> requires implementing a <a class="reference internal" href="../autograd.html#torch.autograd.Function" title="torch.autograd.Function"><code class="xref py py-class docutils literal notranslate"><span class="pre">Function</span></code></a>
that performs the operation and can compute the gradient. From now on let’s
assume that we want to implement a <code class="docutils literal notranslate"><span class="pre">Linear</span></code> module and we have the function
implemented as in the listing above. There’s very little code required to
add this. Now, there are two functions that need to be implemented:</p>
<ul class="simple">
<li><p><code class="docutils literal notranslate"><span class="pre">__init__</span></code> (<em>optional</em>) - takes in arguments such as kernel sizes, numbers
of features, etc. and initializes parameters and buffers.</p></li>
<li><p><a class="reference internal" href="../generated/torch.nn.Module.html#torch.nn.Module.forward" title="torch.nn.Module.forward"><code class="xref py py-meth docutils literal notranslate"><span class="pre">forward()</span></code></a> - instantiates a <a class="reference internal" href="../autograd.html#torch.autograd.Function" title="torch.autograd.Function"><code class="xref py py-class docutils literal notranslate"><span class="pre">Function</span></code></a> and
uses it to perform the operation. It’s very similar to a functional wrapper
shown above.</p></li>
</ul>
<p>This is how a <code class="docutils literal notranslate"><span class="pre">Linear</span></code> module can be implemented:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="k">class</span> <span class="nc">Linear</span><span class="p">(</span><span class="n">nn</span><span class="o">.</span><span class="n">Module</span><span class="p">):</span>
<span class="k">def</span> <span class="fm">__init__</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">input_features</span><span class="p">,</span> <span class="n">output_features</span><span class="p">,</span> <span class="n">bias</span><span class="o">=</span><span class="kc">True</span><span class="p">):</span>
<span class="nb">super</span><span class="p">()</span><span class="o">.</span><span class="fm">__init__</span><span class="p">()</span>
<span class="bp">self</span><span class="o">.</span><span class="n">input_features</span> <span class="o">=</span> <span class="n">input_features</span>
<span class="bp">self</span><span class="o">.</span><span class="n">output_features</span> <span class="o">=</span> <span class="n">output_features</span>
<span class="c1"># nn.Parameter is a special kind of Tensor, that will get</span>
<span class="c1"># automatically registered as Module's parameter once it's assigned</span>
<span class="c1"># as an attribute. Parameters and buffers need to be registered, or</span>
<span class="c1"># they won't appear in .parameters() (doesn't apply to buffers), and</span>
<span class="c1"># won't be converted when e.g. .cuda() is called. You can use</span>
<span class="c1"># .register_buffer() to register buffers.</span>
<span class="c1"># nn.Parameters require gradients by default.</span>
<span class="bp">self</span><span class="o">.</span><span class="n">weight</span> <span class="o">=</span> <span class="n">nn</span><span class="o">.</span><span class="n">Parameter</span><span class="p">(</span><span class="n">torch</span><span class="o">.</span><span class="n">empty</span><span class="p">(</span><span class="n">output_features</span><span class="p">,</span> <span class="n">input_features</span><span class="p">))</span>
<span class="k">if</span> <span class="n">bias</span><span class="p">:</span>