# ===============================================
# RX 480 Prismatic Recursion Benchmark
# ===============================================
import pyopencl as cl
import numpy as np
import time
import math

# ---------------------------
# GPU Setup
# ---------------------------
platform = cl.get_platforms()[0]
device = [d for d in platform.get_devices() if "AMD" in d.name][0]
ctx = cl.Context([device])
queue = cl.CommandQueue(ctx)

print("GPU:", device.name)
print("VRAM (MB):", device.global_mem_size // 1024**2)
print("Compute Units:", device.max_compute_units)
print("Clock (MHz):", device.max_clock_frequency)

# ---------------------------
# Recursive Expansion Model
# ---------------------------
def expansion(depth):
    return 8**depth

def total_instances(depth):
    return expansion(depth) * 131072  # 131072 = safe base from 8 GB VRAM

# ---------------------------
# Kernel (dummy recursion FLOPs)
# ---------------------------
kernel_code = """
__kernel void recurse(
    __global float *data,
    const int expansion)
{
    int gid = get_global_id(0);
    float x = data[gid];
    // simulate prismatic recursion math
    for(int i=0; i<expansion; i++){
        x = sqrt(x * 1.618f + 0.5f) * 1.0001f;
    }
    data[gid] = x;
}
"""
program = cl.Program(ctx, kernel_code).build()

# ---------------------------
# Benchmark Loop
# ---------------------------
for depth in range(1, 11):
    N = min(total_instances(depth), 2**20)  # clamp for demo
    expansion_factor = expansion(depth)

    # Allocate buffer
    data = np.random.rand(N).astype(np.float32)
    buf = cl.Buffer(ctx, cl.mem_flags.READ_WRITE | cl.mem_flags.COPY_HOST_PTR, hostbuf=data)

    # Warmup
    evt = program.recurse(queue, (N,), None, buf, np.int32(expansion_factor))
    evt.wait()

    # Timed run
    t0 = time.time()
    for _ in range(5):
        evt = program.recurse(queue, (N,), None, buf, np.int32(expansion_factor))
    evt.wait()
    dt = (time.time() - t0) / 5.0

    fps = 1.0 / dt
    vram_mb = data.nbytes / 1024**2
    flops = (N * expansion_factor) / dt / 1e9

    print(f"Depth {depth:2d} | N={N:,} | VRAM={vram_mb:.1f} MB | {fps:.2f} FPS | {flops:.2f} GFLOPs")

