Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
34 commits
Select commit Hold shift + click to select a range
1bfa176
add fitness && exit quality mechanism
cocolato Mar 31, 2026
2f9438a
Rewrite the code structure
cocolato Apr 1, 2026
709c0a1
address review
cocolato Apr 1, 2026
ef6ac24
address many reviews
cocolato Apr 2, 2026
21f7122
Merge branch 'main' into jit-tracer-fitness
cocolato Apr 2, 2026
b99fe61
optimize some constants
cocolato Apr 2, 2026
d09afb5
fix comment
cocolato Apr 2, 2026
c9957c3
fix constent
cocolato Apr 2, 2026
9447546
reduce frame penalty
cocolato Apr 3, 2026
7d3e4c4
add debug log
cocolato Apr 3, 2026
2c1b5e0
address review
cocolato Apr 3, 2026
2409b2f
address review
cocolato Apr 3, 2026
88a91dc
Merge branch 'python:main' into jit-tracer-fitness
cocolato Apr 4, 2026
4e12f04
Merge branch 'main' into jit-tracer-fitness
cocolato Apr 6, 2026
4bd251e
fine tune parameters
cocolato Apr 6, 2026
1d93208
remove some special cases
cocolato Apr 6, 2026
386c23a
Merge branch 'main' into jit-tracer-fitness
cocolato Apr 10, 2026
83fd8ab
rewrite fitness mechanism
cocolato Apr 10, 2026
c900563
remove static assert
cocolato Apr 10, 2026
97d8be4
Merge branch 'main' into jit-tracer-fitness
cocolato Apr 12, 2026
559b164
Merge branch 'main' into jit-tracer-fitness
cocolato Apr 14, 2026
7a5e1fe
address partial review
cocolato Apr 14, 2026
9324df0
restore slots_rev
cocolato Apr 14, 2026
e69443b
address review
cocolato Apr 14, 2026
751a1d9
Race MAX_TARGET_LENGTH to 800, compute branch after slots, ignore ENT…
Fidget-Spinner Apr 14, 2026
896e4fe
reduce MAX_TARGET_LENGTH
Fidget-Spinner Apr 14, 2026
1364159
fix tests
Fidget-Spinner Apr 14, 2026
9fbec75
fix a bug
Fidget-Spinner Apr 14, 2026
76b9c9e
magic numbers
Fidget-Spinner Apr 14, 2026
d565f41
lint
Fidget-Spinner Apr 14, 2026
598d332
reduce the trace length to less than half
Fidget-Spinner Apr 14, 2026
64f3468
Address review
Fidget-Spinner Apr 15, 2026
7661e7b
Reduce ENTER_EXECUTOR's exit quality
Fidget-Spinner Apr 15, 2026
9c75bb6
Merge branch 'main' into jit-tracer-fitness
cocolato Apr 16, 2026
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions Include/cpython/pystats.h
Original file line number Diff line number Diff line change
Expand Up @@ -144,6 +144,7 @@ typedef struct _optimization_stats {
uint64_t unknown_callee;
uint64_t trace_immediately_deopts;
uint64_t executors_invalidated;
uint64_t fitness_terminated_traces;
UOpStats opcode[PYSTATS_MAX_UOP_ID + 1];
uint64_t unsupported_opcode[256];
uint64_t trace_length_hist[_Py_UOP_HIST_SIZE];
Expand Down
3 changes: 3 additions & 0 deletions Include/internal/pycore_interp_structs.h
Original file line number Diff line number Diff line change
Expand Up @@ -449,6 +449,9 @@ typedef struct _PyOptimizationConfig {
uint16_t side_exit_initial_value;
uint16_t side_exit_initial_backoff;

// Trace fitness thresholds
uint16_t fitness_initial;

// Optimization flags
bool specialization_enabled;
bool uops_optimize_enabled;
Expand Down
46 changes: 45 additions & 1 deletion Include/internal/pycore_optimizer.h
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,49 @@ extern "C" {
#include "pycore_optimizer_types.h"
#include <stdbool.h>

/* Fitness controls how long a trace can grow.
* Starts at FITNESS_INITIAL, then decreases from per-bytecode buffer usage
* plus branch/frame heuristics. The trace stops when fitness drops below the
* current exit_quality.
*
* Design targets for the constants below:
* 1. Reaching the abstract frame-depth limit should drop fitness below
* EXIT_QUALITY_SPECIALIZABLE.
* 2. A backward edge should leave budget for roughly N_BACKWARD_SLACK more
* bytecodes, assuming AVG_SLOTS_PER_INSTRUCTION.
* 3. Roughly seven balanced branches should reduce fitness to
* EXIT_QUALITY_DEFAULT after per-slot costs.
* 4. A push followed by a matching return is net-zero on frame-specific
* fitness, excluding per-slot costs.
*/
#define MAX_TARGET_LENGTH (UOP_MAX_TRACE_LENGTH / 5 * 2)
#define OPTIMIZER_EFFECTIVENESS 2
#define FITNESS_INITIAL (MAX_TARGET_LENGTH * OPTIMIZER_EFFECTIVENESS)

/* Exit quality thresholds: trace stops when fitness < exit_quality.
* Higher = trace is more willing to stop here. */
#define EXIT_QUALITY_CLOSE_LOOP (FITNESS_INITIAL - AVG_SLOTS_PER_INSTRUCTION*4)
#define EXIT_QUALITY_ENTER_EXECUTOR (FITNESS_INITIAL * 1 / 8)
#define EXIT_QUALITY_DEFAULT (FITNESS_INITIAL / 8)
Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I'd increase this to make sure that the fitness cannot drop from above EXIT_QUALITY_DEFAULT to below EXIT_QUALITY_SPECIALIZABLE in a single uop.

#define EXIT_QUALITY_SPECIALIZABLE (FITNESS_INITIAL / 80)

/* Estimated buffer slots per bytecode, used only to derive heuristics.
* Runtime charging uses trace-buffer capacity consumed for each bytecode. */
#define AVG_SLOTS_PER_INSTRUCTION 6

/* Heuristic backward-edge exit quality: leave room for about 1 unroll and
* N_BACKWARD_SLACK more bytecodes before reaching EXIT_QUALITY_CLOSE_LOOP,
* based on AVG_SLOTS_PER_INSTRUCTION. */
#define N_BACKWARD_SLACK 10
#define EXIT_QUALITY_BACKWARD_EDGE (EXIT_QUALITY_CLOSE_LOOP / 2 - N_BACKWARD_SLACK * AVG_SLOTS_PER_INSTRUCTION)
Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

NOTE:

The problem here is that when tracing loops, we are treating the start of the loop as the closing point, but we want to stop at the end of the loop otherwise.
We probably need to make the back edge quality calculation a bit more complex.

  • if the jump is to the loop closing point: exit_quality = 0 (to ensure loop is closed)
  • otherwise: exit_quality = high ~(FITNESS - 10 * AVG_SLOTS_PER_INSTRUCTION)

(this can be fixed in a separate PR if would complicate this PR too much)

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I prefer to do this in next PR.


/* Penalty for a perfectly balanced (50/50) branch.
* 7 such branches (after per-slot cost) exhaust fitness to EXIT_QUALITY_DEFAULT.
* The calculation assumes the branches are spread out roughly equally throughout the trace.
*/
#define FITNESS_BRANCH_BALANCED ((FITNESS_INITIAL - EXIT_QUALITY_DEFAULT - \
(MAX_TARGET_LENGTH / 7 * AVG_SLOTS_PER_INSTRUCTION)) / (7))


typedef struct _PyJitUopBuffer {
_PyUOpInstruction *start;
Expand Down Expand Up @@ -103,7 +146,8 @@ typedef struct _PyJitTracerPreviousState {
} _PyJitTracerPreviousState;

typedef struct _PyJitTracerTranslatorState {
int jump_backward_seen;
int32_t fitness; // Current trace fitness, starts high, decrements
int frame_depth; // Current inline depth (0 = root frame)
} _PyJitTracerTranslatorState;

typedef struct _PyJitTracerState {
Expand Down
8 changes: 6 additions & 2 deletions Lib/test/test_capi/test_opt.py
Original file line number Diff line number Diff line change
Expand Up @@ -1358,9 +1358,13 @@ def testfunc(n):
for _ in gen(n):
pass
testfunc(TIER2_THRESHOLD * 2)
# The generator may be inlined into testfunc's trace,
# so check whichever executor contains _YIELD_VALUE.
gen_ex = get_first_executor(gen)
self.assertIsNotNone(gen_ex)
uops = get_opnames(gen_ex)
testfunc_ex = get_first_executor(testfunc)
ex = gen_ex or testfunc_ex
self.assertIsNotNone(ex)
uops = get_opnames(ex)
self.assertNotIn("_MAKE_HEAP_SAFE", uops)
self.assertIn("_YIELD_VALUE", uops)

Expand Down
7 changes: 5 additions & 2 deletions Modules/_testinternalcapi/test_cases.c.h

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

7 changes: 5 additions & 2 deletions Python/bytecodes.c
Original file line number Diff line number Diff line change
Expand Up @@ -3503,7 +3503,7 @@ dummy_func(
int og_oparg = (oparg & ~255) | executor->vm_data.oparg;
next_instr = this_instr;
if (_PyJit_EnterExecutorShouldStopTracing(og_opcode)) {
if (_PyOpcode_Caches[_PyOpcode_Deopt[opcode]]) {
if (_PyOpcode_Caches[_PyOpcode_Deopt[og_opcode]]) {
PAUSE_ADAPTIVE_COUNTER(this_instr[1].counter);
}
opcode = og_opcode;
Expand Down Expand Up @@ -6415,7 +6415,10 @@ dummy_func(
tracer->prev_state.instr_frame = frame;
tracer->prev_state.instr_oparg = oparg;
tracer->prev_state.instr_stacklevel = PyStackRef_IsNone(frame->f_executable) ? 2 : STACK_LEVEL();
if (_PyOpcode_Caches[_PyOpcode_Deopt[opcode]]) {
if (_PyOpcode_Caches[_PyOpcode_Deopt[opcode]]
Comment thread
cocolato marked this conversation as resolved.
// Branch opcodes use the cache for branch history, not
// specialization counters. Don't reset it.
&& !IS_CONDITIONAL_JUMP_OPCODE(opcode)) {
(&next_instr[1])->counter = trigger_backoff_counter();
}

Expand Down
7 changes: 5 additions & 2 deletions Python/generated_cases.c.h

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

Loading
Loading