Repository navigation
Expand file tree
/
Copy patheval_frame.c
More file actions
900 lines (777 loc) · 28.3 KB
/
Copy patheval_frame.c
File metadata and controls
900 lines (777 loc) · 28.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
#define PY_SSIZE_T_CLEAN
#include <signal.h>
#include <torch/csrc/dynamo/cpp_shim.h>
#include <torch/csrc/dynamo/cpython_defs.h>
#include <torch/csrc/dynamo/cpython_includes.h>
#include <torch/csrc/dynamo/debug_macros.h>
#include <torch/csrc/dynamo/eval_frame.h>
#include <torch/csrc/dynamo/eval_frame_cpp.h>
#include <torch/csrc/utils/python_compat.h>
#if IS_PYTHON_3_14_PLUS && defined(_WIN32)
#define Py_BUILD_CORE
#include <internal/pycore_code.h>
#include <internal/pycore_interpframe.h>
#include <internal/pycore_stackref.h>
#undef Py_BUILD_CORE
#endif
PyObject* guard_error_hook = NULL;
PyObject* guard_complete_hook = NULL;
typedef struct {
int active_dynamo_threads;
} ModuleState;
static Py_tss_t eval_frame_callback_key = Py_tss_NEEDS_INIT;
// The flags below all describe "the Dynamo region this thread is currently
// inside". Stored as per-thread tagged pointers.
static Py_tss_t isolate_recompiles_key = Py_tss_NEEDS_INIT; // int64_t
static Py_tss_t skip_guard_eval_key = Py_tss_NEEDS_INIT; // bool
static Py_tss_t fullgraph_count_key = Py_tss_NEEDS_INIT; // int64_t
static Py_tss_t fullgraph_error_key = Py_tss_NEEDS_INIT; // bool
// TSS slots hold a void*. NULL means "never set on this thread" and that's the
// default. Scalars are stored biased by +2 so that no real value collides with
// NULL. Tagged scalars need no heap allocation, so reads and writes are
// GIL-free and there is nothing to free at thread exit.
static void* tag_int64(int64_t v) {
return (void*)(intptr_t)(v + 2);
}
static int64_t untag_int64(void* p) {
return (int64_t)(intptr_t)p - 2;
}
static void* tag_bool(bool b) {
return tag_int64((int64_t)b);
}
static bool untag_bool(void* p) {
return (bool)untag_int64(p);
}
static int64_t get_isolate_recompiles_id_raw(Py_tss_t* key) {
void* p = PyThread_tss_get(key);
return p == NULL ? -1 : untag_int64(p);
}
static void set_isolate_recompiles_id_raw(Py_tss_t* key, int64_t id) {
PyThread_tss_set(key, tag_int64(id));
}
static bool get_skip_guard_eval_raw(Py_tss_t* key) {
void* p = PyThread_tss_get(key);
return p == NULL ? false : untag_bool(p);
}
static void set_skip_guard_eval_raw(Py_tss_t* key, bool v) {
PyThread_tss_set(key, tag_bool(v));
}
// -1 means inactive, >= 0 means active with that many compiled frames.
static int get_fullgraph_count_raw(Py_tss_t* key) {
void* p = PyThread_tss_get(key);
return p == NULL ? -1 : (int)untag_int64(p);
}
static void set_fullgraph_count_raw(Py_tss_t* key, int v) {
PyThread_tss_set(key, tag_int64((int64_t)v));
}
// When true and fullgraph_compiled_frame_count > 0, sub-frames under fullgraph
// compilation will error (via get_fail_callback) instead of being silently
// skipped.
static bool get_fullgraph_error_raw(Py_tss_t* key) {
void* p = PyThread_tss_get(key);
return p == NULL ? false : untag_bool(p);
}
static void set_fullgraph_error_raw(Py_tss_t* key, bool v) {
PyThread_tss_set(key, tag_bool(v));
}
bool get_skip_guard_eval_unsafe(void) {
return get_skip_guard_eval_raw(&skip_guard_eval_key);
}
int get_fullgraph_compiled_frame_count(void) {
return get_fullgraph_count_raw(&fullgraph_count_key);
}
void bump_fullgraph_compiled_frame_count(void) {
void* p = PyThread_tss_get(&fullgraph_count_key);
if (p != NULL) {
PyThread_tss_set(&fullgraph_count_key, tag_int64(untag_int64(p) + 1));
}
}
bool get_fullgraph_error_on_nested_compile(void) {
return get_fullgraph_error_raw(&fullgraph_error_key);
}
PyObject* eval_frame_callback_get(void) {
void* result = PyThread_tss_get(&eval_frame_callback_key);
if (unlikely(result == NULL)) {
return (PyObject*)Py_None;
} else {
return (PyObject*)result;
}
}
void eval_frame_callback_set(PyObject* obj) {
PyThread_tss_set(&eval_frame_callback_key, obj);
}
int64_t get_current_isolate_recompiles_id(void) {
return get_isolate_recompiles_id_raw(&isolate_recompiles_key);
}
static void set_current_isolate_recompiles_id(int64_t id) {
set_isolate_recompiles_id_raw(&isolate_recompiles_key, id);
}
static PyObject* get_eval_frame_isolate_recompiles_id_py(
PyObject* dummy,
PyObject* args) {
return PyLong_FromLongLong(get_current_isolate_recompiles_id());
}
static PyObject* set_eval_frame_isolate_recompiles_id_py(
PyObject* dummy,
PyObject* arg) {
if (!PyLong_Check(arg)) {
PyErr_SetString(PyExc_TypeError, "expected an int");
return NULL;
}
int64_t new_id = PyLong_AsLongLong(arg);
if (new_id == -1 && PyErr_Occurred()) {
return NULL;
}
int64_t old_id = get_current_isolate_recompiles_id();
set_current_isolate_recompiles_id(new_id);
return PyLong_FromLongLong(old_id);
}
// 3.16 Not supported at all. See cpython_defs.c for hints
#if !(IS_PYTHON_3_16_PLUS)
#define DECLARE_PYOBJ_ATTR(name) \
static PyObject* THPPyInterpreterFrame_##name( \
THPPyInterpreterFrame* self, PyObject* _noargs) { \
PyObject* res = (PyObject*)self->frame->name; \
Py_XINCREF(res); \
return res; \
}
DECLARE_PYOBJ_ATTR(f_globals)
DECLARE_PYOBJ_ATTR(f_builtins)
static PyObject* THPPyInterpreterFrame_f_locals(
THPPyInterpreterFrame* self,
PyObject* _noargs) {
DEBUG_NULL_CHECK(self->locals);
Py_XINCREF(self->locals);
return self->locals;
}
#if IS_PYTHON_3_14_PLUS
static PyObject* THPPyInterpreterFrame_f_executable(
THPPyInterpreterFrame* self,
PyObject* _noargs) {
if (PyStackRef_IsNull(self->frame->f_executable)) {
Py_RETURN_NONE;
}
return PyStackRef_AsPyObjectNew(self->frame->f_executable);
}
#elif IS_PYTHON_3_13_PLUS
DECLARE_PYOBJ_ATTR(f_executable)
#else
DECLARE_PYOBJ_ATTR(f_code)
#endif
#undef DECLARE_PYOBJ_ATTR
// This is not a true attribute of the class but we do access it in python and
// it is hard to implement on the python side, so do it here:
static PyObject* THPPyInterpreterFrame_f_lasti(
THPPyInterpreterFrame* self,
PyObject* _noargs) {
return PyLong_FromLong(_PyInterpreterFrame_LASTI(self->frame));
}
static PyObject* THPPyInterpreterFrame_f_lineno(
THPPyInterpreterFrame* self,
PyObject* _noargs) {
if (!self->frame->frame_obj) {
return PyLong_FromLong(F_CODE(self->frame)->co_firstlineno);
}
int lineno = PyFrame_GetLineNumber(self->frame->frame_obj);
if (lineno < 0) {
Py_RETURN_NONE;
}
return PyLong_FromLong(lineno);
}
static PyObject* THPPyInterpreterFrame_f_back(
THPPyInterpreterFrame* self,
PyObject* _noargs) {
if (!self->frame->frame_obj) {
Py_RETURN_NONE;
}
return (PyObject*)PyFrame_GetBack(self->frame->frame_obj);
}
static PyObject* THPPyInterpreterFrame_closure(
THPPyInterpreterFrame* self,
PyObject* _noargs) {
PyObject* closure = FUNC(self->frame)->func_closure;
return closure == NULL ? PyTuple_New(0) : Py_XNewRef(closure);
}
// NOLINTNEXTLINE(cppcoreguidelines-avoid-c-arrays,cppcoreguidelines-avoid-non-const-global-variables,modernize-avoid-c-arrays)
static struct PyGetSetDef THPPyInterpreterFrame_properties[] = {
{"f_globals", (getter)THPPyInterpreterFrame_f_globals, NULL, NULL, NULL},
{"f_builtins", (getter)THPPyInterpreterFrame_f_builtins, NULL, NULL, NULL},
{"f_locals", (getter)THPPyInterpreterFrame_f_locals, NULL, NULL, NULL},
#if IS_PYTHON_3_13_PLUS
{"f_code", (getter)THPPyInterpreterFrame_f_executable, NULL, NULL, NULL},
#else
{"f_code", (getter)THPPyInterpreterFrame_f_code, NULL, NULL, NULL},
#endif
{"f_lasti", (getter)THPPyInterpreterFrame_f_lasti, NULL, NULL, NULL},
{"f_lineno", (getter)THPPyInterpreterFrame_f_lineno, NULL, NULL, NULL},
{"f_back", (getter)THPPyInterpreterFrame_f_back, NULL, NULL, NULL},
{"closure", (getter)THPPyInterpreterFrame_closure, NULL, NULL, NULL},
{NULL}};
static PyTypeObject THPPyInterpreterFrameType = {
PyVarObject_HEAD_INIT(NULL, 0)
.tp_name = "torch._C._dynamo.eval_frame._PyInterpreterFrame",
.tp_basicsize = sizeof(THPPyInterpreterFrame),
.tp_flags = Py_TPFLAGS_DEFAULT,
.tp_getset = THPPyInterpreterFrame_properties,
};
THPPyInterpreterFrame* THPPyInterpreterFrame_New(
THP_EVAL_API_FRAME_OBJECT* frame) {
PyTypeObject* type = (PyTypeObject*)&THPPyInterpreterFrameType;
THPPyInterpreterFrame* self = (THPPyInterpreterFrame*)type->tp_alloc(type, 0);
if (!self)
return NULL;
self->frame = frame;
self->locals = NULL;
return self;
}
static PyObject* dynamo__custom_eval_frame_shim(
PyThreadState* tstate,
THP_EVAL_API_FRAME_OBJECT* frame,
int throw_flag);
static PyObject* (*previous_eval_frame)(
PyThreadState* tstate,
THP_EVAL_API_FRAME_OBJECT* frame,
int throw_flag) = NULL;
static PyObject* dynamo_custom_eval_frame_shim(
PyThreadState* tstate,
THP_EVAL_API_FRAME_OBJECT* frame,
int throw_flag) {
return dynamo__custom_eval_frame_shim(tstate, frame, throw_flag);
}
PyObject* dynamo_eval_frame_default(
PyThreadState* tstate,
THP_EVAL_API_FRAME_OBJECT* frame,
int throw_flag) {
if (tstate == NULL) {
tstate = PyThreadState_GET();
}
if (previous_eval_frame) {
return previous_eval_frame(tstate, frame, throw_flag);
} else {
return _PyEval_EvalFrameDefault(tstate, frame, throw_flag);
}
}
static void enable_eval_frame_shim(PyThreadState* tstate) {
if (_PyInterpreterState_GetEvalFrameFunc(tstate->interp) !=
&dynamo_custom_eval_frame_shim) {
DEBUG_CHECK(previous_eval_frame == NULL);
previous_eval_frame = _PyInterpreterState_GetEvalFrameFunc(tstate->interp);
_PyInterpreterState_SetEvalFrameFunc(
tstate->interp, &dynamo_custom_eval_frame_shim);
}
}
static void enable_eval_frame_default(PyThreadState* tstate) {
if (_PyInterpreterState_GetEvalFrameFunc(tstate->interp) !=
previous_eval_frame) {
DEBUG_CHECK(previous_eval_frame != NULL);
_PyInterpreterState_SetEvalFrameFunc(tstate->interp, previous_eval_frame);
previous_eval_frame = NULL;
}
}
const char* get_frame_name(THP_EVAL_API_FRAME_OBJECT* frame) {
// Returns the C string name of the current frame.
DEBUG_CHECK(PyUnicode_Check(F_CODE(frame)->co_name));
return PyUnicode_AsUTF8(F_CODE(frame)->co_name);
}
#if IS_PYTHON_3_14_PLUS
static void dup_obj(_PyStackRef* dst, _PyStackRef src) {
if (PyStackRef_IsNull(src)) {
*dst = PyStackRef_NULL;
} else {
*dst = PyStackRef_DUP(src);
}
}
#else
static void dup_obj(PyObject** dst, PyObject* src) {
Py_XINCREF(src);
*dst = src;
}
#endif
static PyObject* dynamo_eval_custom_code_impl(
PyThreadState* tstate,
THP_EVAL_API_FRAME_OBJECT* frame,
PyCodeObject* code,
int throw_flag) {
DEBUG_NULL_CHECK(tstate);
DEBUG_NULL_CHECK(frame);
DEBUG_NULL_CHECK(code);
// Generate Python function object and _PyInterpreterFrame in a way similar to
// https://github.com/python/cpython/blob/e715da6db1d1d70cd779dc48e1ba8110c51cc1bf/Python/ceval.c#L1130
PyFunctionObject* old_func = FUNC(frame);
#if IS_PYTHON_3_12_PLUS
size_t size = code->co_framesize;
#else
size_t size = code->co_nlocalsplus + code->co_stacksize + FRAME_SPECIALS_SIZE;
#endif
PyFunctionObject* func = _PyFunction_CopyWithNewCode(old_func, code);
if (func == NULL) {
return NULL;
}
THP_EVAL_API_FRAME_OBJECT* shadow =
THP_PyThreadState_BumpFramePointerSlow(tstate, size);
if (shadow == NULL) {
Py_DECREF(func);
return NULL;
}
Py_INCREF(func);
// consumes reference to func
#if IS_PYTHON_3_14_PLUS
_PyStackRef func_stackref = PyStackRef_FromPyObjectSteal((PyObject*)func);
_PyFrame_Initialize(
tstate, shadow, func_stackref, NULL, code, 0, frame->previous);
#elif IS_PYTHON_3_12_PLUS
_PyFrame_Initialize(shadow, func, NULL, code, 0);
#else
_PyFrame_InitializeSpecials(shadow, func, NULL, code->co_nlocalsplus);
#endif
#if IS_PYTHON_3_14_PLUS
_PyStackRef* fastlocals_old = frame->localsplus;
_PyStackRef* fastlocals_new = shadow->localsplus;
#else
PyObject** fastlocals_old = frame->localsplus;
PyObject** fastlocals_new = shadow->localsplus;
#endif
Py_ssize_t n_old = F_CODE(frame)->co_nlocalsplus;
Py_ssize_t n_new = code->co_nlocalsplus;
// localsplus are XINCREF'd by default eval frame, so all values must be
// valid.
#if !(IS_PYTHON_3_12_PLUS)
// _PyFrame_Initialize in 3.12 already does this
for (int i = 0; i < code->co_nlocalsplus; i++) {
fastlocals_new[i] = NULL;
}
#endif
// ============== Initialize new frame from old frame ============
// Python internal for executing a function:
// 1. CPython interpreter first creates an empty frame according to the code
// object
// 2. CPython interpreter initializes the frame by filling arguments/free
// variables into frame and initializing cell variables
// 3. CPython interpreter executes the code object
//
// Dynamo hooks the 3rd step: before executing the code object, Dynamo
// transforms the code object into a new code object. Then, the old frame is
// not suitable for executing the new code. Therefore, Dynamo needs to
// manually create and initialize a new frame to execute the new code. The
// main task is to copy data in old frame to new frame, concerning a storage
// space named `localsplus`.
//
// localsplus storage is an array with the following layout:
// | args | new_locals | cell_variables | free_variables |
// | <--- from left to right, index from 0 to n - 1 ---> |
// code.co_varnames == args + new_locals, code.co_nlocals ==
// len(code.co_varnames) code.co_freevars == free_variables, and `n <=
// code.co_nlocals + len(code.co_cellvars) + len(code.co_freevars)` (Python
// expression). There is an extra field in Python C-API: `n ==
// code->co_nlocalsplus` (C expression) to retrieve the length of array. The
// complexity happens if an argument becomes a cell variable:
// `code.co_cellvars > cell_variables`, that cell variable is still stored in
// args, with a flag set in corresponding item's `co_localspluskinds` .
//
// ideally, we need to look up new localsplus from old localsplus by name:
// for i, name, value in enumerate(localsplusnames_old):
// if value != NULL: (NULL happens for new local variables and arguments
// that becomes cell variables)
// name_to_idx[name] = i
// for i, name in enumerate(localsplusnames_new):
// if name in name_to_idx:
// fastlocals_new[i] = fastlocals_old[name_to_idx[name]]
//
// The above process of building a `name_to_idx` mapping is expensive.
// Dynamo makes the following assumptions:
// 1. new code has the same arguments as the old code (both the number and
// the order)
// 2. new code has the same cell variables as the old code (both the number
// and the order)
// 3. new code has the same free variables as the old code (both the number
// and the order) The only flexibility lies in new local variables: new code
// can introduce their own variables.
// With these assumptions, Dynamo can copy data directly by index. Dynamo just
// needs to take care of copying cell variables correctly. To avoid runtime
// cost, the assumptions are checked when we first generate the code object in
// pytorch/torch/_dynamo/convert_frame.py .
// copy args
// according to https://docs.python.org/3/library/inspect.html , `co_argcount`
// is the number of arguments (not including keyword only arguments, * or **
// args). so we need to add `co_kwonlyargcount` and `co_flags` to get the
// total number of arguments.
// !!(F_CODE(frame)->co_flags & CO_VARARGS) is 1 if the function has *args, 0
// otherwise
// !!(F_CODE(frame)->co_flags & CO_VARKEYWORDS) is 1 if the function has
// **kwargs, 0 otherwise they convert bit flags to 0 or 1, and avoid
// branching. This is performance critical code, so we really care about
// performance.
Py_ssize_t total_argcount_old = F_CODE(frame)->co_argcount +
F_CODE(frame)->co_kwonlyargcount +
!!(F_CODE(frame)->co_flags & CO_VARARGS) +
!!(F_CODE(frame)->co_flags & CO_VARKEYWORDS);
for (Py_ssize_t i = 0; i < total_argcount_old; i++) {
dup_obj(&fastlocals_new[i], fastlocals_old[i]);
}
// copy free vars
Py_ssize_t nfrees_old = PyCode_GetNFreevars(F_CODE(frame));
for (Py_ssize_t i = 0; i < nfrees_old; i++) {
dup_obj(&fastlocals_new[n_new - 1 - i], fastlocals_old[n_old - 1 - i]);
}
// copy cell vars, from high index to low index, until it meets a variable
// that is not cell variable.
for (Py_ssize_t i = n_old - nfrees_old - 1, j = n_new - nfrees_old - 1;
i >= total_argcount_old;
i--, j--) {
// conditional test to tell if a variable is not a cell variable, using the
// bit flags in `co_localspluskinds`.
if (!(_PyLocals_GetKind(F_CODE(frame)->co_localspluskinds, i) &
CO_FAST_CELL)) {
break;
}
dup_obj(&fastlocals_new[j], fastlocals_old[i]);
}
// NOTE: if you want to evaluate frame instead of shadow in 3.12+,
// you need to clear_old_frame_if_python_312_plus the shadow frame BEFORE
// calling eval_frame_default (i.e. here) and comment out the
// clear_old_frame_if_python_312_plus call on the original frame.
PyObject* result = dynamo_eval_frame_default(tstate, shadow, throw_flag);
#if IS_PYTHON_3_12_PLUS
// frame is cleared by caller
Py_DECREF(func);
#else
// In 3.11, shadow has is_entry set to true, so _PyEvalFrameClearAndPop is not
// called, so we manually clear and pop the shadow frame.
THP_PyFrame_Clear(shadow);
THP_PyThreadState_PopFrame(tstate, shadow);
Py_DECREF(func);
#endif
return result;
}
// This wrapper function adds a profiler event
PyObject* dynamo_eval_custom_code(
PyThreadState* tstate,
THP_EVAL_API_FRAME_OBJECT* frame,
PyCodeObject* code,
const char* trace_annotation,
int throw_flag) {
_PytorchRecordFunctionState* rf =
_pytorch_record_function_enter(trace_annotation);
PyObject* result =
dynamo_eval_custom_code_impl(tstate, frame, code, throw_flag);
_pytorch_record_function_exit(rf);
return result;
}
static PyObject* dynamo__custom_eval_frame_shim(
PyThreadState* tstate,
THP_EVAL_API_FRAME_OBJECT* frame,
int throw_flag) {
// Shims logic into one of three states. Can probably be refactored into a
// single func, later:
// - None: disables TorchDynamo
// - False: run-only mode (reuse existing compiles)
// - Python callable(): enables TorchDynamo
PyObject* callback = eval_frame_callback_get();
if (Py_IsNone(callback)) {
return dynamo_eval_frame_default(tstate, frame, throw_flag);
}
return dynamo__custom_eval_frame(tstate, frame, throw_flag, callback);
}
#else // !(IS_PYTHON_3_15_PLUS)
// Fake definitions for everything we removed
static void enable_eval_frame_shim(PyThreadState* tstate) {}
static void enable_eval_frame_default(PyThreadState* tstate) {}
PyObject* dynamo_eval_custom_code(
PyThreadState* tstate,
THP_EVAL_API_FRAME_OBJECT* frame,
PyCodeObject* code,
const char* trace_annotation,
int throw_flag) {
return NULL;
}
THPPyInterpreterFrame* THPPyInterpreterFrame_New(
THP_EVAL_API_FRAME_OBJECT* frame) {
return NULL;
}
PyObject* dynamo_eval_frame_default(
PyThreadState* tstate,
THP_EVAL_API_FRAME_OBJECT* frame,
int throw_flag) {
return NULL;
}
static struct PyGetSetDef THPPyInterpreterFrame_properties[] = {{NULL}};
static PyTypeObject THPPyInterpreterFrameType = {
PyVarObject_HEAD_INIT(NULL, 0)
.tp_name = "torch._C._dynamo.eval_frame._PyInterpreterFrame",
.tp_basicsize = sizeof(THPPyInterpreterFrame),
.tp_flags = Py_TPFLAGS_DEFAULT,
.tp_getset = THPPyInterpreterFrame_properties,
};
#endif // !(IS_PYTHON_3_15_PLUS)
#if !IS_PYTHON_3_13_PLUS
void clear_old_frame_if_python_312_plus(
PyThreadState* tstate,
THP_EVAL_API_FRAME_OBJECT* frame) {
#if IS_PYTHON_3_12_PLUS
THP_PyFrame_Clear(frame);
THP_PyThreadState_PopFrame(tstate, frame);
#endif
}
#endif // !IS_PYTHON_3_13_PLUS
static PyObject* increment_working_threads(
PyThreadState* tstate,
PyObject* module) {
ModuleState* state = PyModule_GetState(module);
if (state != NULL) {
state->active_dynamo_threads = state->active_dynamo_threads + 1;
if (state->active_dynamo_threads > 0) {
enable_eval_frame_shim(tstate);
}
}
Py_RETURN_NONE;
}
static PyObject* decrement_working_threads(
PyThreadState* tstate,
PyObject* module) {
ModuleState* state = PyModule_GetState(module);
if (state != NULL) {
if (state->active_dynamo_threads > 0) {
state->active_dynamo_threads = state->active_dynamo_threads - 1;
if (state->active_dynamo_threads == 0) {
enable_eval_frame_default(tstate);
}
}
}
Py_RETURN_NONE;
}
PyObject* dynamo_set_eval_frame(PyObject* new_callback, PyObject* module) {
// Change the eval frame callback and return the old one
// - None: disables TorchDynamo
// - False: run-only mode (reuse existing compiles)
// - Python callable(): enables TorchDynamo
PyObject* old_callback = eval_frame_callback_get();
// Common case: if Dynamo is actually off, we might see a lot of
// traffic setting the callback to None when it was already
// None. Skip messing with threading, thread-local storage, and
// reference counts.
if (old_callback != new_callback) {
if (Py_IsNone(new_callback)) {
decrement_working_threads(PyThreadState_GET(), module);
} else {
increment_working_threads(PyThreadState_GET(), module);
}
Py_INCREF(new_callback);
// Set thread local callback. This will drive behavior of our shim, if/when
// it is installed.
eval_frame_callback_set(new_callback);
// Transfer owned reference from eval_frame_callback_get() to caller
// without Py_DECREF/Py_INCREF.
} else {
// We retain a reference to old_callback because it's still the
// eval_frame_callback, so we need to give the caller their
// own reference.
Py_INCREF(old_callback);
}
return old_callback;
}
static PyObject* set_eval_frame_py(PyObject* module, PyObject* callback) {
if (!Py_IsNone(callback) && !Py_IsFalse(callback) &&
!PyCallable_Check(callback)) {
DEBUG_TRACE0("arg error");
PyErr_SetString(PyExc_TypeError, "expected a callable");
return NULL;
}
DEBUG_TRACE(
"python enabled=%d and is run_only=%d",
!Py_IsNone(callback),
Py_IsFalse(callback));
return dynamo_set_eval_frame(callback, module);
}
static PyObject* set_skip_guard_eval_unsafe(
PyObject* dummy,
PyObject* skip_guard_unsafe_flag) {
if (!Py_IsFalse(skip_guard_unsafe_flag) && !Py_IsTrue(skip_guard_unsafe_flag)) {
DEBUG_TRACE0("arg error");
PyErr_SetString(PyExc_TypeError, "expected True/False");
return NULL;
}
bool old_skip_guard_eval_unsafe =
get_skip_guard_eval_raw(&skip_guard_eval_key);
set_skip_guard_eval_raw(
&skip_guard_eval_key, Py_IsTrue(skip_guard_unsafe_flag));
if (old_skip_guard_eval_unsafe) {
Py_RETURN_TRUE;
}
Py_RETURN_FALSE;
}
static PyObject* get_eval_frame_callback_py(PyObject* dummy, PyObject* args) {
// New reference
PyObject* callback = eval_frame_callback_get();
return Py_NewRef(callback);
}
static PyObject* reset_code(PyObject* dummy, PyObject* code) {
if (!PyCode_Check(code)) {
DEBUG_TRACE0("arg error");
PyErr_SetString(PyExc_TypeError, "expected a code object");
return NULL;
}
// set_extra_state destroys the existing object on extra scratch space.
set_extra_state((PyCodeObject*)code, NULL);
Py_RETURN_NONE;
}
static PyObject* unsupported(PyObject* dummy, PyObject* args) {
// a dummy C function used in testing
PyObject* obj1 = NULL;
PyObject* obj2 = NULL;
if (!PyArg_ParseTuple(args, "OO", &obj1, &obj2)) {
return NULL;
}
return Py_NewRef(obj2);
}
static PyObject* set_guard_error_hook(PyObject* dummy, PyObject* obj) {
if (Py_IsNone(obj)) {
obj = NULL;
}
Py_XSETREF(guard_error_hook, Py_XNewRef(obj));
Py_RETURN_NONE;
}
static PyObject* set_guard_complete_hook(PyObject* dummy, PyObject* obj) {
PyObject* old_hook = guard_complete_hook;
if (Py_IsNone(obj)) {
obj = NULL;
}
guard_complete_hook = Py_XNewRef(obj);
if (old_hook == NULL) {
Py_RETURN_NONE;
} else {
return old_hook;
}
}
// Debugging function for GNU C only.
// Used to set gdb breakpoints in hot CPython sites from Python.
// Code example:
//
// def foo(x):
// x = x + 1
// torch._dynamo.eval_frame.raise_sigtrap()
// # (gdb) b bytecodes.c:1234 (whatever line CALL is handled)
// x = torch.sin(x) # gdb breakpoint hit when sin is called
//
// In this example, we want to breakpoint on CALL in bytecodes.c only when
// running foo. Otherwise, we would need to breakpoint before running the
// program, and that breakpoint would be hit every time Python makes a function
// call, leading to a spammy debugging experience.
static PyObject* raise_sigtrap(PyObject* dummy, PyObject* obj) {
#ifdef __GNUC__
raise(SIGTRAP);
#endif
Py_RETURN_NONE;
}
static int clear_state(PyObject* module) {
ModuleState* state = PyModule_GetState(module);
if (state) {
state->active_dynamo_threads = 0;
return 0;
}
return -1;
}
// Set the fullgraph compiled frame counter and return the old value.
// If setting to >= 0 (activating) and already active, no-op.
static PyObject* set_fullgraph_compiled_frame_count_py(
PyObject* dummy,
PyObject* arg) {
long val = PyLong_AsLong(arg);
if (val == -1 && PyErr_Occurred()) {
return NULL;
}
int old = get_fullgraph_count_raw(&fullgraph_count_key);
if (val >= 0 && old >= 0) {
// Already active, no-op.
} else {
set_fullgraph_count_raw(&fullgraph_count_key, (int)val);
}
return PyLong_FromLong(old);
}
// Set fullgraph_error_on_nested_compile and return the old value.
static PyObject* set_fullgraph_error_on_nested_compile_py(
PyObject* dummy,
PyObject* arg) {
if (!Py_IsFalse(arg) && !Py_IsTrue(arg)) {
PyErr_SetString(PyExc_TypeError, "expected True/False");
return NULL;
}
bool old = get_fullgraph_error_raw(&fullgraph_error_key);
set_fullgraph_error_raw(&fullgraph_error_key, Py_IsTrue(arg));
if (old) {
Py_RETURN_TRUE;
}
Py_RETURN_FALSE;
}
static PyMethodDef _methods[] = {
{"set_eval_frame", set_eval_frame_py, METH_O, NULL},
{"set_skip_guard_eval_unsafe", set_skip_guard_eval_unsafe, METH_O, NULL},
{"get_eval_frame_callback", get_eval_frame_callback_py, METH_NOARGS, NULL},
{"reset_code", reset_code, METH_O, NULL},
{"unsupported", unsupported, METH_VARARGS, NULL},
{"set_code_exec_strategy",
dynamo_set_code_exec_strategy,
METH_VARARGS,
NULL},
{"set_guard_error_hook", set_guard_error_hook, METH_O, NULL},
{"set_guard_complete_hook", set_guard_complete_hook, METH_O, NULL},
{"raise_sigtrap", raise_sigtrap, METH_NOARGS, NULL},
{"set_fullgraph_compiled_frame_count",
set_fullgraph_compiled_frame_count_py,
METH_O,
NULL},
{"set_fullgraph_error_on_nested_compile",
set_fullgraph_error_on_nested_compile_py,
METH_O,
NULL},
{"set_eval_frame_isolate_recompiles_id", set_eval_frame_isolate_recompiles_id_py, METH_O, NULL},
{"get_eval_frame_isolate_recompiles_id", get_eval_frame_isolate_recompiles_id_py, METH_NOARGS, NULL},
{NULL, NULL, 0, NULL}};
static struct PyModuleDef _module = {
PyModuleDef_HEAD_INIT,
.m_name = "torch._C._dynamo.eval_frame",
.m_doc = "Module containing hooks to override eval_frame",
.m_size = sizeof(ModuleState),
.m_methods = _methods,
.m_clear = clear_state};
#if IS_PYTHON_3_12_PLUS
#define _PyEval_RequestCodeExtraIndex PyUnstable_Eval_RequestCodeExtraIndex
#endif
PyObject* torch_c_dynamo_eval_frame_init(void) {
extra_index = _PyEval_RequestCodeExtraIndex(destroy_extra_state);
if (extra_index < 0) {
PyErr_SetString(
PyExc_RuntimeError, "dynamo: unable to register extra index");
return NULL;
}
int result = PyThread_tss_create(&eval_frame_callback_key);
CHECK(result == 0);
Py_INCREF(Py_None);
eval_frame_callback_set(Py_None);
PyObject* module = PyModule_Create(&_module);
if (module == NULL) {
return NULL;
}
Py_tss_t* keys[] = {
&isolate_recompiles_key,
&skip_guard_eval_key,
&fullgraph_count_key,
&fullgraph_error_key};
for (size_t i = 0; i < sizeof(keys) / sizeof(keys[0]); i++) {
if (PyThread_tss_create(keys[i]) != 0) {
for (size_t j = 0; j < i; j++) {
PyThread_tss_delete(keys[j]);
}
Py_DECREF(module);
PyErr_SetString(
PyExc_RuntimeError, "dynamo: unable to create TSS key");
return NULL;
}
}
#ifdef Py_GIL_DISABLED
PyUnstable_Module_SetGIL(module, Py_MOD_GIL_NOT_USED);
#endif
if (PyModule_AddType(module, &THPPyInterpreterFrameType) < 0) {
return NULL;
}
return module;
}