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
 
 
 
 
 
 
 
 
 
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
# ============================================================
# F1 PIT LANE - MODEL LATENCY BENCHMARK
#
# Measures:
#   1. XGBoost inference only
#   2. Preprocessing + XGBoost inference
#   3. Batch prediction for 20 drivers
#
# IMPORTANT:
#   The benchmark loads the SAME .pkl used by the backend.
# ============================================================

import time
from pathlib import Path

import joblib
import numpy as np
import pandas as pd


# ============================================================
# CONFIGURATION
# ============================================================

MODEL_PATH = (
    "C:\\Users\\Admin\\Desktop\\PitLane\\F1_Model\\f1_live_winner_model.pkl"
)

DATASET_PATH = (
    "C:\\Users\\Admin\\Desktop\\PitLane\\F1_Model\\F1_2026_model_training_data.csv"
)

# Number of measured repetitions
N_RUNS = 1000

# Warm-up predictions are NOT included in the measurements.
WARMUP_RUNS = 100


# ============================================================
# LOAD MODEL
# ============================================================

print("=" * 80)
print("F1 PIT LANE - MODEL LATENCY BENCHMARK")
print("=" * 80)

if not Path(MODEL_PATH).exists():

    raise FileNotFoundError(
        f"Model not found:\n{MODEL_PATH}"
    )


print("\nLoading model bundle...")

bundle = joblib.load(
    MODEL_PATH
)

model = bundle["model"]
preprocessor = bundle["preprocessor"]
feature_columns = bundle["feature_columns"]

print(
    f"Model loaded successfully."
)

print(
    f"Expected features: "
    f"{len(feature_columns)}"
)


# ============================================================
# LOAD REAL DATA
#
# We use your actual model-training dataset rather than
# synthetic/random values.
# ============================================================

if not Path(DATASET_PATH).exists():

    raise FileNotFoundError(
        f"Dataset not found:\n{DATASET_PATH}"
    )


print("\nLoading real feature data...")

df = pd.read_csv(
    DATASET_PATH,
    low_memory=False
)


# ============================================================
# PREPARE ONE REAL MODEL INPUT ROW
# ============================================================

# ------------------------------------------------------------
# Remove target / metadata exactly as the training pipeline
# does.
# ------------------------------------------------------------

DROP_COLUMNS = [
    "Winner",
    "RaceDate",

    "winning_driver_number",
    "WinningDriver",
    "WinningDriverName",

    "RaceID",
    "session_key",
    "meeting_key",
    "location",
    "country_name",
    "RoundNumber",
    "EventName",

    "_RaceDate"
]


X = df.drop(
    columns=[
        column
        for column in DROP_COLUMNS
        if column in df.columns
    ],
    errors="ignore"
)


# ------------------------------------------------------------
# Ensure exact feature order
# ------------------------------------------------------------

for column in feature_columns:

    if column not in X.columns:

        X[column] = np.nan


X = X[
    feature_columns
]


# Take one real driver/lap row
one_row = X.iloc[[0]].copy()


print(
    f"\nOne-row shape: "
    f"{one_row.shape}"
)


# ============================================================
# PREPROCESS ONCE
#
# This allows us to measure pure XGBoost inference separately.
# ============================================================

one_row_processed = (
    preprocessor.transform(
        one_row
    )
)


# ============================================================
# 1. XGBOOST-ONLY LATENCY
# ============================================================

print("\n")
print("=" * 80)
print("1. XGBOOST INFERENCE ONLY")
print("=" * 80)


# Warm-up
for _ in range(WARMUP_RUNS):

    model.predict_proba(
        one_row_processed
    )


latencies_ms = []


for _ in range(N_RUNS):

    start = time.perf_counter_ns()

    model.predict_proba(
        one_row_processed
    )

    end = time.perf_counter_ns()

    latency = (
        end - start
    ) / 1_000_000

    latencies_ms.append(
        latency
    )


latencies_ms = np.array(
    latencies_ms
)


print(
    f"Mean : "
    f"{latencies_ms.mean():.4f} ms"
)

print(
    f"Min  : "
    f"{latencies_ms.min():.4f} ms"
)

print(
    f"Max  : "
    f"{latencies_ms.max():.4f} ms"
)

print(
    f"P50  : "
    f"{np.percentile(latencies_ms, 50):.4f} ms"
)

print(
    f"P95  : "
    f"{np.percentile(latencies_ms, 95):.4f} ms"
)

print(
    f"P99  : "
    f"{np.percentile(latencies_ms, 99):.4f} ms"
)


# ============================================================
# 2. PREPROCESSING + XGBOOST
# ============================================================

print("\n")
print("=" * 80)
print("2. PREPROCESSING + XGBOOST")
print("=" * 80)


# Warm-up
for _ in range(WARMUP_RUNS):

    processed = (
        preprocessor.transform(
            one_row
        )
    )

    model.predict_proba(
        processed
    )


latencies_ms = []


for _ in range(N_RUNS):

    start = time.perf_counter_ns()

    processed = (
        preprocessor.transform(
            one_row
        )
    )

    model.predict_proba(
        processed
    )

    end = time.perf_counter_ns()

    latency = (
        end - start
    ) / 1_000_000

    latencies_ms.append(
        latency
    )


latencies_ms = np.array(
    latencies_ms
)


print(
    f"Mean : "
    f"{latencies_ms.mean():.4f} ms"
)

print(
    f"Min  : "
    f"{latencies_ms.min():.4f} ms"
)

print(
    f"Max  : "
    f"{latencies_ms.max():.4f} ms"
)

print(
    f"P50  : "
    f"{np.percentile(latencies_ms, 50):.4f} ms"
)

print(
    f"P95  : "
    f"{np.percentile(latencies_ms, 95):.4f} ms"
)

print(
    f"P99  : "
    f"{np.percentile(latencies_ms, 99):.4f} ms"
)


# ============================================================
# 3. 20-DRIVER BATCH LATENCY
#
# This is much more relevant to your actual Pit Lane system.
#
# We take 20 real rows and predict all 20 together.
# ============================================================

print("\n")
print("=" * 80)
print("3. 20-DRIVER BATCH LATENCY")
print("=" * 80)


# ------------------------------------------------------------
# Take up to 20 real rows
# ------------------------------------------------------------

batch_size = min(
    20,
    len(X)
)

batch = X.iloc[
    :batch_size
].copy()


# Warm-up
for _ in range(WARMUP_RUNS):

    processed = (
        preprocessor.transform(
            batch
        )
    )

    model.predict_proba(
        processed
    )


latencies_ms = []


for _ in range(N_RUNS):

    start = time.perf_counter_ns()

    processed = (
        preprocessor.transform(
            batch
        )
    )

    model.predict_proba(
        processed
    )

    end = time.perf_counter_ns()

    latency = (
        end - start
    ) / 1_000_000

    latencies_ms.append(
        latency
    )


latencies_ms = np.array(
    latencies_ms
)


print(
    f"Drivers measured: "
    f"{batch_size}"
)

print(
    f"Mean total : "
    f"{latencies_ms.mean():.4f} ms"
)

print(
    f"P50 total  : "
    f"{np.percentile(latencies_ms, 50):.4f} ms"
)

print(
    f"P95 total  : "
    f"{np.percentile(latencies_ms, 95):.4f} ms"
)

print(
    f"P99 total  : "
    f"{np.percentile(latencies_ms, 99):.4f} ms"
)

print(
    f"\nApprox. per-driver mean: "
    f"{latencies_ms.mean() / batch_size:.4f} ms"
)


# ============================================================
# 4. PREDICTION OUTPUT CHECK
# ============================================================

print("\n")
print("=" * 80)
print("PREDICTION CHECK")
print("=" * 80)


processed = (
    preprocessor.transform(
        batch
    )
)

probabilities = (
    model.predict_proba(
        processed
    )[:, 1]
)


print(
    "\nPredicted probabilities:"
)

for i, probability in enumerate(
    probabilities
):

    print(
        f"Driver row {i + 1:02d}: "
        f"{probability * 100:.4f}%"
    )


# ============================================================
# 5. FINAL SUMMARY
# ============================================================

print("\n")
print("=" * 80)
print("LATENCY BENCHMARK COMPLETE")
print("=" * 80)

print(
    "\nThese measurements exclude:"
)

print(
    "  - network latency"
)

print(
    "  - API/FastF1 latency"
)

print(
    "  - raw telemetry acquisition"
)

print(
    "  - raw telemetry → compressed-lap processing"
)

print(
    "\nTherefore the 20-driver batch number is the "
    "model-side latency, NOT the total backend latency."
)