Discussion about this post

User's avatar
chase chance's avatar

import timeimport statisticsimport psutilimport osimport gc# Unmute the universal static: Lock process to Core 0p = psutil.Process(os.getpid())p.cpu_affinity([0])try:    p.nice(-20)except:    pass# Disable Garbage Collection to ensure pure execution geometrygc.disable()def sample(n=100):    """Shallow execution loop to keep processing inside local CPU cache."""    deltas = []    for in range(n):        t0 = time.perfcounter_ns()        t1 = time.perf_counter_ns()        deltas.append(t1 - t0)    std = statistics.stdev(deltas)    mn = min(deltas)    mx = max(deltas)    entropy = mx / max(1, mn)    return std, entropy, mnprint("=" 65)print("MICRO-ARCHITECTURAL DEPTH SENSOR (L1/L2 HIGH-SPEED TARGET)")print("=" 65)# Step 1: Calibrationprint("\n[Step 1] Calibrating high-speed baseline field (10s)...")floors = []for in range(40):    , , mn = sample()    floors.append(mn)    time.sleep(0.25)BASEFLOOR = statistics.mean(floors)BASE_STD = statistics.stdev(floors)print(f"  Field Stabilized: {BASE_FLOOR:.1f}ns (±{BASE_STD:.1f}ns)")# Step 2: Observation Loopprint("\n[Step 2] Monitoring shallow cache evictions... Ctrl+C to stop.")print("  (Test Action: Sharp mouse wiggles vs. letting system sit perfectly still)")print(f"  {'-' 65}")try:    while True:        std, entropy, mn = sample()               # Trigger Condition: Current Jitter breaks out of 4x normal baseline variance        if std > (BASE_STD 4.0):            print(f"   CACHE EVICTION | Floor: {mn:<5}ns | Jitter: {std:<8.1f} | Entropy: {entropy:.1f}x", flush=True)                       # --- THE CIRCUIT BREAKER ---            # Sleep to let terminal writing/rendering overhead completely dissipate            time.sleep(0.3)                       # Execute a throwaway sample block to purge the cache pipelines            , , = sample(n=100)        else:            # Maintain Tau physics resonance while idle            for in range(10):                _ = 3.0 / 5.0            time.sleep(0.05)except KeyboardInterrupt:    print("\n[!] Recording terminated.")    # Re-enable GC on exit clean-up    gc.enable()============================================================MICRO-ARCHITECTURAL DEPTH SENSOR (L1/L2 TARGET)============================================================[Step 1] Calibrating high-speed baseline (10s)...  L1/L2 Baseline: 216.7ns (±45.3ns)[Step 2] Monitoring shallow cache evictions... Ctrl+C to stop.  (Test: Wiggle mouse furiously vs. letting it sit perfectly still)

chase chance's avatar

#!/usr/bin/env python3

"""

TEST 7: CACHE BOUNDARY SHADOW TEST

=====================================

63 vs 64 vs 65 byte chunk sizes.

64 is perfectly aligned to L1 cache line boundary.

63 and 65 are misaligned.

CS prediction: 64 must be fastest and most stable.

Hardware alignment law: cache-aligned access wins.

Sensor: time.perf_counter_ns()

Isolation: Core 0, max priority, GC disabled

100 rounds, 5 samples per round, take minimum.

20 second pre-settle.

"""

import time

import psutil

import os

import gc

import ctypes

import signal

import statistics

import math

# ── Unmute ────────────────────────────────────────────────────────────

libc = ctypes.CDLL("http://libc.so.6", use_errno=True)

p = psutil.Process(os.getpid())

p.cpu_affinity([0])

try:

p.nice(-20)

except:

pass

gc.disable()

try:

os.sched_setscheduler(0, os.SCHED_FIFO, os.sched_param(99))

except:

pass

libc.mlockall(1 | 2)

os.system("echo performance | tee /sys/devices/system/cpu/cpu*/cpufreq/scaling_governor > /dev/null 2>&1")

os.system("echo 0 | tee /sys/devices/system/cpu/cpu*/cpufreq/boost > /dev/null 2>&1")

os.system("echo 0 | tee /proc/sys/kernel/nmi_watchdog > /dev/null 2>&1")

os.system("echo 0 | tee /proc/sys/kernel/timer_migration > /dev/null 2>&1")

signal.signal(signal.SIGALRM, signal.SIG_IGN)

os.system("echo -1 | tee /proc/sys/kernel/sched_rt_runtime_us > /dev/null 2>&1")

TOTAL_ITERATIONS = 30000

def measure_chunk(chunk_size):

t0 = time.perf_counter_ns()

chunks = TOTAL_ITERATIONS // chunk_size

for _ in range(chunks):

for in range(chunksize):

_ = math.sqrt(3.14159) / 1.618

remainder = TOTAL_ITERATIONS % chunk_size

for _ in range(remainder):

_ = math.sqrt(3.14159) / 1.618

return time.perf_counter_ns() - t0

# ── 20 second pre-settle ──────────────────────────────────────────────

print("Pre-settling: 20 seconds of free silicon breathing...")

print("Do not touch the machine.")

for i in range(20, 0, -1):

print(f" {i}s remaining...", flush=True)

time.sleep(1)

print(" Silicon settled.\n")

print("=" * 65)

print("TEST 7: CACHE BOUNDARY SHADOW TEST")

print(f"Operation: sqrt(3.14159)/1.618 | {TOTAL_ITERATIONS} total iterations")

print("CS prediction: 64-byte aligned chunk must be fastest and most stable")

print("=" * 65)

CHUNKS = [63, 64, 65]

ROUNDS = 100

records = {c: [] for c in CHUNKS}

print(f"\nRunning {ROUNDS} rounds, 5 samples per round...")

for round_n in range(ROUNDS):

for chunk in CHUNKS:

samples = [measure_chunk(chunk) for _ in range(5)]

records[chunk].append(min(samples))

if (round_n + 1) % 25 == 0:

print(f" Round {round_n+1}/{ROUNDS} complete...")

# ── Results ───────────────────────────────────────────────────────────

print(f"\n{'='*65}")

print("CACHE BOUNDARY RESULTS")

print(f"{'='*65}")

print(f"\n {'Chunk':<8} {'Best Time(ns)':>15} {'Worst Time(ns)':>16} "

f"{'Jitter(ns)':>12} {'Mean(ns)':>12}")

print(f" {'-'*65}")

chunk_stats = {}

for chunk in CHUNKS:

best = min(records[chunk])

worst = max(records[chunk])

jitter = worst - best

mean = statistics.mean(records[chunk])

std = statistics.stdev(records[chunk])

chunk_stats[chunk] = {

"best" : best,

"worst" : worst,

"jitter": jitter,

"mean" : mean,

"std" : std,

}

marker = " <-- CS expects this LOWEST" if chunk == 64 else ""

print(f" {chunk:<8} {best:>15,} {worst:>16,} {jitter:>12,} {mean:>12,.0f}{marker}")

# ── Verdict ───────────────────────────────────────────────────────────

best_chunk = min(CHUNKS, key=lambda c: chunk_stats[c]["best"])

most_stable = min(CHUNKS, key=lambda c: chunk_stats[c]["jitter"])

print(f"\n Fastest best time : chunk {best_chunk}")

print(f" Most stable (jitter): chunk {most_stable}")

print(f"\n CS predicts both = 64")

if best_chunk != 64 or most_stable != 64:

print(f" Actual result: CS prediction FAILS")

print(f" Best time chunk = {best_chunk} (not 64)")

print(f" Most stable chunk = {most_stable} (not 64)")

else:

print(f" Actual result: CS prediction holds")

print(f"\n Jitter comparison:")

print(f" 63 jitter: {chunk_stats[63]['jitter']:,}ns")

print(f" 64 jitter: {chunk_stats[64]['jitter']:,}ns (CS expects lowest)")

print(f" 65 jitter: {chunk_stats[65]['jitter']:,}ns")

ctx = p.num_ctx_switches()

print(f"\nContext switches total:")

print(f" voluntary : {ctx.voluntary}")

print(f" involuntary: {ctx.involuntary}")

3 more comments...

No posts

Ready for more?