In this section
- GPU Score transform · gpu-drivers-for-global-grid / cuda-maths/layout-bench/gpu_score.py lines 1–232
- Control other · gpu-drivers-for-global-grid / cuda-maths/precision-sense/control.py lines 1–26
- Control2 other · gpu-drivers-for-global-grid / cuda-maths/precision-sense/control2.py lines 1–33
- Cpu100m other · gpu-drivers-for-global-grid / cuda-maths/precision-sense/cpu100m.py lines 1–11
- Sense storage · gpu-drivers-for-global-grid / cuda-maths/precision-sense/sense.py lines 1–266
- East West Block other · gpu-drivers-for-global-grid / engine/east_west_block.py lines 1–111
GPU Score
A Python module in the layout bench folder of GPU Drivers for Global Grid that scores batch (`score_batch`). It is built from the pack windows helper (`pack_windows`).
transformgpu-drivers-for-global-grid / cuda-maths/layout-bench/gpu_score.py · lines 1–232 of 232
- What it does
- It calculates its inputs. Defines pack_windows, _occupied, score_batch. Uses libraries itertools, math, os, numpy, cupy.
- Why it exists in the grid workflow
- Domain stage sub33kv_design (path word 'layout'): inside-the-fence electrical and civil design below 33kV, which Ventus Ltd states is within its commercial execution boundary.
- Downstream impact
- Used directly by 1 file: Bench (gpu-drivers-for-global-grid).
- What it achieves
- Batched layout scorer: the exact integer score of `layout_search`.score_window, for all 40 windows, as tensor ops.
- Why it matters
- Imported by Bench.
- Application
- gpu-drivers-for-global-grid · cuda-maths/layout-bench · Python module
- Uses
- itertools, math, os, numpy, cupy
- Used by
- imported by Bench (import)
- Produces
- pack_windows, score_batch
- Defines here
- pack_windows, _occupied, score_batch
- Cannot conclude
- Whether this code runs, is used by a live app today, or is correct. This is a static reading.
- Evidence
- gpu-drivers-for-global-grid@6c47912a8dde251ffebd92ff129e6a0c11c4ebfe cuda-maths/layout-bench/gpu_score.py:1-232 · blob 801ee9242802c7f1ebfb724939317b00a6279396 · GitHub at these lines
- State
- achieves: comment · context: readme_derived · stage: transform · effects: none found · domain stage: sub33kv_design · users: EPC_contractor, ICP_grid_engineer · canonical: unknown
"""Batched layout scorer: the exact integer score of layout_search.score_window,
for all 40 windows, as tensor ops. Runs on the GPU with CuPy or on one CPU core
with NumPy (xp is chosen at import time by GPU_BENCH_BACKEND).
Every term of the CPU scorer is implemented: lattice snap, collision ring search
(displacement), octilinear error, dropped links, missing nodes, segment
crossings, and label-slot overlap. Nothing is left out.
Shape of the trick: the batch of parameter points is the parallel axis. The 40
windows and the 3 hop subsets are a 120-group Python loop (their node/link sets
differ), and inside each group the node-placement loop and the label loop are
still SEQUENTIAL over nodes, because both read an occupancy set that earlier
nodes wrote. That data dependence is the whole story of this benchmark.
"""
import itertools
import math
import os
import numpy as np
BACKEND = os.environ.get("GPU_BENCH_BACKEND", "numpy")
if BACKEND == "cupy":
import cupy as xp
else:
xp = np
N_PITCH, N_ROT, N_LAB, N_COL, N_OFX, N_OFY, N_HOP, N_SIM = 24, 16, 24, 16, 16, 16, 3, 12
SPACE = N_PITCH * N_ROT * N_LAB * N_COL * N_OFX * N_OFY * N_HOP * N_SIM
STRIDE = 1000003
W_LABEL, W_CROSS, W_OCT, W_DISP = 8, 5, 2, 1
W_DROP, W_MISS = 6, 4
NB = [(1, 0), (1, 1), (0, 1), (-1, 1), (-1, 0), (-1, -1), (0, -1), (1, -1)]
COLL_ORDERS = [[NB[(j * (1 + 2 * (o % 4)) + o) % 8] for j in range(8)] for o in range(16)]
LAB_SLOTS = [(1, 0), (-1, 0), (0, 1), (0, -1)]
LAB_ORDERS = [list(p) for p in itertools.permutations(range(4))]
ROT_COS = [int(round(1024 * math.cos(math.radians(r * 3.0)))) for r in range(N_ROT)]
ROT_SIN = [int(round(1024 * math.sin(math.radians(r * 3.0)))) for r in range(N_ROT)]
PITCH_M = [500 + p * 500 for p in range(N_PITCH)]
I8 = np.int64
KMUL = 1 << 20 # cell key = gx * KMUL + gy
SENT = -(1 << 60) # empty occupancy slot
_PITCH = xp.asarray(PITCH_M, I8)
_COS = xp.asarray(ROT_COS, I8)
_SIN = xp.asarray(ROT_SIN, I8)
_ORDX = xp.asarray([[a for (a, b) in o] for o in COLL_ORDERS], I8) # (16,8)
_ORDY = xp.asarray([[b for (a, b) in o] for o in COLL_ORDERS], I8)
_LABORD = xp.asarray(LAB_ORDERS, I8) # (24,4)
_SLOTX = xp.asarray([s[0] for s in LAB_SLOTS], I8)
_SLOTY = xp.asarray([s[1] for s in LAB_SLOTS], I8)
def pack_windows(windows):
"""Pre-flatten each (window, hop) group into static arrays."""
groups = []
for w in windows:
for h in range(3):
sub = w["subs"][h]
pos = {n: k for k, n in enumerate(sub)}
S = len(sub)
xs = np.array([w["x"][n] for n in sub], I8)
ys = np.array([w["y"][n] for n in sub], I8)
lw = np.array([w["lw"][n] for n in sub], I8)
act, base_drop = [], 0
for (a, b, km100) in w["links"]:
if a in pos and b in pos:
act.append((pos[a], pos[b], km100))
else:
base_drop += 1
la = np.array([t[0] for t in act], I8)
lb = np.array([t[1] for t in act], I8)
lkm = np.array([t[2] for t in act], I8)
L = len(act)
pi, pj = np.triu_indices(L, 1) if L > 1 else (np.array([], I8), np.array([], I8))
# static layout of the occupancy table: S node cells, then lw[j] label
# cells for each node j in order (0 for unnamed nodes).
lab_at, c = [], S
for j in range(S):
lab_at.append(c)
c += int(lw[j])
groups.append({
"w": w, "h": h, "S": S, "L": L, "M": c,
"xs": xp.asarray(xs), "ys": xp.asarray(ys),
"lw": [int(v) for v in lw], "lab_at": lab_at,
"la": xp.asarray(la), "lb": xp.asarray(lb), "lkm": xp.asarray(lkm),
"pi": xp.asarray(pi.astype(np.int64)), "pj": xp.asarray(pj.astype(np.int64)),
"base_drop": base_drop, "miss": w["n"] - S,
})
return groups
def _occupied(occ, upto, key):
"""key: (B,) or (B,C). True where key is present in occ[:, :upto]."""
if upto <= 0:
return xp.zeros(key.shape, dtype=bool)
o = occ[:, :upto]
if key.ndim == 1:
return (o == key[:, None]).any(axis=1)
return (o[:, :, None] == key[:, None, :]).any(axis=1)
def score_batch(idxs, groups):
"""idxs: (B,) int64 parameter indices. Returns (B,) int64 total score."""
i = idxs
p = i % N_PITCH; i = i // N_PITCH
r = i % N_ROT; i = i // N_ROT
lo = i % N_LAB; i = i // N_LAB
co = i % N_COL; i = i // N_COL
ox = i % N_OFX; i = i // N_OFX
oy = i % N_OFY; i = i // N_OFY
hp = i % N_HOP; i = i // N_HOP
sm = i % N_SIM
B = idxs.shape[0]
pitch = _PITCH[p]
cs = _COS[r]; sn = _SIN[r]
dx0 = (ox * pitch) // N_OFX
dy0 = (oy * pitch) // N_OFY
ordx = _ORDX[co]; ordy = _ORDY[co] # (B,8)
slots = _LABORD[lo] # (B,4) slot ids
minkm = sm * 150
total = xp.zeros(B, I8)
for g in groups:
m = (hp == g["h"])
sel = xp.nonzero(m)[0]
nb = int(sel.shape[0])
if nb == 0:
continue
gp = pitch[sel]; gcs = cs[sel]; gsn = sn[sel]
gdx = dx0[sel]; gdy = dy0[sel]
gox = ordx[sel]; goy = ordy[sel]
gsl = slots[sel]; gmin = minkm[sel]
S = g["S"]; M = g["M"]
occ = xp.full((nb, M), SENT, I8)
cxs = xp.empty((nb, S), I8)
cys = xp.empty((nb, S), I8)
disp = xp.zeros(nb, I8)
# --- lattice snap + collision ring search (sequential over nodes) ---
for j in range(S):
x = g["xs"][j]; y = g["ys"][j]
gx = ((x * gcs + y * gsn) // 1024 + gdx) // gp
gy = ((y * gcs - x * gsn) // 1024 + gdy) // gp
if j > 0:
key = gx * KMUL + gy
coll = _occupied(occ, j, key)
if bool(coll.any()):
placed = xp.zeros(nb, dtype=bool)
live = coll.copy()
for ring in (1, 2, 3):
for t in range(8):
need = live & ~placed
if not bool(need.any()):
break
cxk = gx + gox[:, t] * ring
cyk = gy + goy[:, t] * ring
ck = cxk * KMUL + cyk
free = ~_occupied(occ, j, ck) & need
gx = xp.where(free, cxk, gx)
gy = xp.where(free, cyk, gy)
disp = disp + xp.where(free, I8(ring), I8(0))
placed = placed | free
if not bool((live & ~placed).any()):
break
disp = disp + xp.where(live & ~placed, I8(4), I8(0))
cxs[:, j] = gx
cys[:, j] = gy
occ[:, j] = gx * KMUL + gy
# --- links: drops and octilinear error ---
L = g["L"]
ndrop = xp.full(nb, I8(g["base_drop"]), I8)
oct_err = xp.zeros(nb, I8)
if L:
valid = g["lkm"][None, :] >= gmin[:, None] # (nb,L)
ndrop = ndrop + (~valid).sum(axis=1).astype(I8)
ax = cxs[:, g["la"]]; ay = cys[:, g["la"]]
bx = cxs[:, g["lb"]]; by = cys[:, g["lb"]]
adx = xp.abs(ax - bx); ady = xp.abs(ay - by)
e = xp.where((adx != 0) & (ady != 0) & (adx != ady), xp.abs(adx - ady), I8(0))
oct_err = xp.where(valid, e, I8(0)).sum(axis=1).astype(I8)
# --- crossings over every ordered pair of surviving segments ---
cross = xp.zeros(nb, I8)
if L > 1:
pi = g["pi"]; pj = g["pj"]
Ax = ax[:, pi]; Ay = ay[:, pi]; Bx = bx[:, pi]; By = by[:, pi]
Px = ax[:, pj]; Py = ay[:, pj]; Qx = bx[:, pj]; Qy = by[:, pj]
d1 = (Bx - Ax) * (Py - Ay) - (By - Ay) * (Px - Ax)
d2 = (Bx - Ax) * (Qy - Ay) - (By - Ay) * (Qx - Ax)
d3 = (Qx - Px) * (Ay - Py) - (Qy - Py) * (Ax - Px)
d4 = (Qx - Px) * (By - Py) - (Qy - Py) * (Bx - Px)
hit = ((d1 > 0) != (d2 > 0)) & ((d3 > 0) != (d4 > 0))
hit = hit & valid[:, pi] & valid[:, pj]
cross = hit.sum(axis=1).astype(I8)
# --- label slots (sequential over nodes; writes into the same occupancy) ---
overl = xp.zeros(nb, I8)
for j in range(S):
wdt = g["lw"][j]
if not wdt:
continue
at = g["lab_at"][j]
gx = cxs[:, j]; gy = cys[:, j]
done = xp.zeros(nb, dtype=bool)
bxf = xp.zeros(nb, I8); byf = xp.zeros(nb, I8)
for si in range(4):
sid = gsl[:, si]
sx = _SLOTX[sid]; sy = _SLOTY[sid]
bxs = gx + sx * xp.where(sx >= 0, I8(1), I8(wdt))
bys = gy + sy
offs = xp.arange(wdt, dtype=I8)
ck = (bxs[:, None] + offs[None, :]) * KMUL + bys[:, None]
free = ~_occupied(occ, at, ck).any(axis=1) & ~done
bxf = xp.where(free, bxs, bxf)
byf = xp.where(free, bys, byf)
done = done | free
if bool(done.all()):
break
offs = xp.arange(wdt, dtype=I8)
keys = (bxf[:, None] + offs[None, :]) * KMUL + byf[:, None]
occ[:, at:at + wdt] = xp.where(done[:, None], keys, I8(SENT))
overl = overl + (~done).astype(I8)
s = (W_LABEL * overl + W_CROSS * cross + W_OCT * oct_err + W_DISP * disp
+ W_DROP * ndrop + W_MISS * g["miss"])
total[sel] = total[sel] + s
return totalControl
A Python module in the precision sense folder of GPU Drivers for Global Grid.
othergpu-drivers-for-global-grid / cuda-maths/precision-sense/control.py · lines 1–26 of 26 · Not reached from any entry point (candidate for review)
- What it does
- Uses libraries sys, json, numpy, cupy, solar_core.
- What it achieves
- No statement of purpose was found in the file, a README line naming it, or its name. Described from its file name only (a candidate, not yet checked against the code).
- Why it matters
- No other file in the estate was found to import it.
- Application
- gpu-drivers-for-global-grid · cuda-maths/precision-sense · Python module
- Uses
- sys, json, numpy, cupy, solar_core, cpu_vec, cupyx
- Used by
- none found
- Produces
- none declared
- Defines here
- none
- Cannot conclude
- Whether this code runs, is used by a live app today, or is correct. This is a static reading.
- Evidence
- gpu-drivers-for-global-grid@6c47912a8dde251ffebd92ff129e6a0c11c4ebfe cuda-maths/precision-sense/control.py:1-26 · blob 672dfd6a7ab4f19e05a27cbb5f0ceb8c48c97676 · GitHub at these lines
- State
- achieves: name · context: readme_derived · stage: unknown · effects: none found · domain stage: unknown · users: none · canonical: unreached_review
import sys, json, numpy as np, cupy as cp
sys.path.insert(0, r"(local path removed)")
from solar_core import *
from cpu_vec import build_tables, kernel
from cupyx import scatter_max
T = build_tables(cp); best = cp.zeros(N_CELLS, dtype=cp.int64); done = 0
while done < SPACE:
n = min(1 << 22, SPACE - done)
idx = cp.arange(done, done + n, dtype=cp.int64)
_, pk, cell, _ = kernel(cp, T, idx)
g = pk > 0
if bool(g.any()): scatter_max(best, cell[g], pk[g])
done += n
best = cp.asnumpy(best)
cells = np.arange(N_CELLS); dTn_ = (cells // 120) % 7; dc_ = (cells // 840) % 3
Voc0 = np.array([c[1] for c in CLASSES])[dc_]; beta0 = np.array([c[5] for c in CLASSES])[dc_]
Tmin0 = np.array(axis_values()["Tmin"])[dTn_]
bN = (best >> 44) & 0x3F; hv = best > 0
Nmax = np.floor(1500.0 / (Voc0 * (1.0 + beta0/100.0 * ((Tmin0 + T_ALLOW_K) - 25.0))))
pred = np.minimum(34.0, Nmax); pred = np.where(pred < 20, 0, pred)
ok = (bN == pred) & hv
d = (bN - pred)[hv]
print(json.dumps({"cells": int(hv.sum()), "rule_ok": int(ok.sum()),
"share": float(ok.sum()/hv.sum()), "below_rule": int((d<0).sum()), "above_rule": int((d>0).sum()),
"mean_delta": float(d.mean()), "min_delta": float(d.min()), "max_delta": float(d.max())}))
cp.get_default_memory_pool().free_all_blocks()Control2
A Python module in the precision sense folder of GPU Drivers for Global Grid.
othergpu-drivers-for-global-grid / cuda-maths/precision-sense/control2.py · lines 1–33 of 33 · Not reached from any entry point (candidate for review)
- What it does
- Uses libraries sys, json, numpy, cupy, solar_core.
- What it achieves
- No statement of purpose was found in the file, a README line naming it, or its name. Described from its file name only (a candidate, not yet checked against the code).
- Why it matters
- No other file in the estate was found to import it.
- Application
- gpu-drivers-for-global-grid · cuda-maths/precision-sense · Python module
- Uses
- sys, json, numpy, cupy, solar_core, cpu_vec, cupyx
- Used by
- none found
- Produces
- none declared
- Defines here
- none
- Cannot conclude
- Whether this code runs, is used by a live app today, or is correct. This is a static reading.
- Evidence
- gpu-drivers-for-global-grid@6c47912a8dde251ffebd92ff129e6a0c11c4ebfe cuda-maths/precision-sense/control2.py:1-33 · blob ad3c2a050596636e69e8828b51b45ceb4c57ede8 · GitHub at these lines
- State
- achieves: name · context: readme_derived · stage: unknown · effects: none found · domain stage: unknown · users: none · canonical: unreached_review
import sys, json, numpy as np, cupy as cp
sys.path.insert(0, r"(local path removed)")
from solar_core import *
import cpu_vec
from cpu_vec import build_tables, kernel
from cupyx import scatter_max
AV = axis_values()
SH = dict(AV); SH["L"]=[v+8.125 for v in AV["L"]]; SH["Tcond"]=[v+5.0 for v in AV["Tcond"]]
SH["Tmin"]=[v+2.5 for v in AV["Tmin"]]; SH["Thot"]=[v+2.5 for v in AV["Thot"]]
SH["bif"]=[v+0.025 for v in AV["bif"]]; SH["Rc"]=[0.000375,0.00075,0.00125]
cells=np.arange(N_CELLS); dTn_=(cells//120)%7; dc_=(cells//840)%3
Voc0=np.array([c[1] for c in CLASSES])[dc_]; beta0=np.array([c[5] for c in CLASSES])[dc_]
out={}
for tag,av in (("base",AV),("shifted",SH)):
cpu_vec._AV=av; T=build_tables(cp)
best=cp.zeros(N_CELLS,dtype=cp.int64); done=0
while done<SPACE:
n=min(1<<22,SPACE-done); idx=cp.arange(done,done+n,dtype=cp.int64)
_,pk,cell,_=kernel(cp,T,idx); g=pk>0
if bool(g.any()): scatter_max(best,cell[g],pk[g])
done+=n
best=cp.asnumpy(best); bN=(best>>44)&0x3F; hv=best>0
Tm=np.array(av["Tmin"])[dTn_]
r={}
for rd,allow in (("A_+10K",T_ALLOW_K),("B_no_allowance",0.0)):
Nmax=np.floor(1500.0/(Voc0*(1.0+beta0/100.0*((Tm+allow)-25.0))))
pred=np.minimum(34.0,Nmax); pred=np.where(pred<20,0,pred)
ok=(bN==pred)&hv
exc=np.where(hv&~ok)[0][:10]
r[rd]=dict(share=float(ok.sum()/hv.sum()),ok=int(ok.sum()),exceptions=[int(e) for e in exc])
out[tag]=dict(cells=int(hv.sum()),by_reading=r)
print(json.dumps(out))
cp.get_default_memory_pool().free_all_blocks()Cpu100m
A Python command-line tool in the precision sense folder of GPU Drivers for Global Grid.
othergpu-drivers-for-global-grid / cuda-maths/precision-sense/cpu100m.py · lines 1–11 of 11 · Entry point
- What it does
- Uses libraries sys, json, time, cpu_vec.
- Inputs & outputs
- In: command-line arguments.
- Downstream impact
- Used directly by 1 file: Sense (gpu-drivers-for-global-grid).
- What it achieves
- The CPU vectorised path, 12 workers below normal, own process so the pool's re-import of __main__ cannot touch the GPU script.
- Why it matters
- Run by Sense.
- Application
- gpu-drivers-for-global-grid · cuda-maths/precision-sense · Python CLI
- Uses
- sys, json, time, cpu_vec
- Used by
- run by Sense (script call)
- Produces
- none declared
- Defines here
- none
- Cannot conclude
- Whether this code runs, is used by a live app today, or is correct. This is a static reading.
- Evidence
- gpu-drivers-for-global-grid@6c47912a8dde251ffebd92ff129e6a0c11c4ebfe cuda-maths/precision-sense/cpu100m.py:1-11 · blob 0e1bd6742d95f2ac468b71314ecd6de2dbf7b5f1 · GitHub at these lines
- State
- achieves: comment · context: readme_derived · stage: unknown · effects: none found · domain stage: unknown · users: none · canonical: unknown
# cpu100m.py - the CPU vectorised path, 12 workers below normal, own process so the
# pool's re-import of __main__ cannot touch the GPU script.
import sys, json, time
sys.path.insert(0, r"(local path removed)")
if __name__ == "__main__":
import multiprocessing; multiprocessing.freeze_support()
import cpu_vec
n = int(sys.argv[1])
t0 = time.time()
counts, _ = cpu_vec.run_multiproc(n, workers=12)
print(json.dumps({"counts": [int(x) for x in counts], "seconds": time.time() - t0}))Sense
A Python module in the precision sense folder of GPU Drivers for Global Grid that works with free batch (`free_batch`). It is built from the watts class (`Watts`).
storagegpu-drivers-for-global-grid / cuda-maths/precision-sense/sense.py · lines 1–266 of 266 · Not reached from any entry point (candidate for review) · pattern free_batch (shared by 3 files)
- What it does
- It loads data. Defines 10 functions or classes, including XP32, __init__, __getattr__, Watts, __init__. Uses libraries sys, os, json, time, threading. Side effects: reads or writes files; starts processes.
- Inputs & outputs
- In: JSON file SENSE.json. Out: JSON file.
- What it achieves
- GPU sense checks that could EMBARRASS the solar-billion result.
- Why it matters
- No other file in the estate was found to import it.
- Application
- gpu-drivers-for-global-grid · cuda-maths/precision-sense · Python module
- Uses
- Cpu100m (script call), sys, os, json, time, threading, subprocess, numpy, cupy
- Used by
- none found
- Produces
- XP32, Watts, free_batch
- Defines here
- XP32, __init__, __getattr__, Watts, __init__, _loop, __enter__, __exit__, free_batch, _dump
- Cannot conclude
- Whether this code runs, is used by a live app today, or is correct. This is a static reading.
- Evidence
- gpu-drivers-for-global-grid@6c47912a8dde251ffebd92ff129e6a0c11c4ebfe cuda-maths/precision-sense/sense.py:1-266 · blob 23d88d48baf0579026b191643691e66d3244b419 · GitHub at these lines
- State
- achieves: comment · context: readme_derived · stage: output · effects: filesystem, process · domain stage: unknown · users: none · canonical: unreached_review
# sense.py - GPU sense checks that could EMBARRASS the solar-billion result.
# Reuses (local path removed) arithmetic unchanged (solar_core, cpu_vec.kernel).
import sys, os, json, time, threading, subprocess
sys.path.insert(0, r"(local path removed)")
import numpy as np
import cupy as cp
from solar_core import *
import cpu_vec
from cpu_vec import build_tables, kernel
OUT = r"(local path removed)"
PLACE = []
_p = 1
for r in RADIX:
PLACE.append(_p); _p *= r
class XP32:
"""Proxy so build_tables/kernel run in float32 without editing the originals."""
def __init__(self, xp): self._xp = xp
def __getattr__(self, k):
if k == "float64": return self._xp.float32
return getattr(self._xp, k)
# ---- power sampling around each GPU burst -------------------------------
class Watts:
def __init__(self): self.s = []; self.go = False
def _loop(self):
while self.go:
try:
o = subprocess.run(["nvidia-smi", "--query-gpu=power.draw",
"--format=csv,noheader,nounits"],
capture_output=True, text=True, timeout=5).stdout
self.s.append(float(o.strip().split("\n")[0]))
except Exception: pass
time.sleep(0.25)
def __enter__(self):
self.go = True; self.t0 = time.time()
self.th = threading.Thread(target=self._loop, daemon=True); self.th.start(); return self
def __exit__(self, *a):
cp.cuda.Stream.null.synchronize()
self.secs = time.time() - self.t0; self.go = False; self.th.join(timeout=2)
self.watts = float(np.mean(self.s)) if self.s else float("nan")
def free_batch(div=2.0, cap=1 << 21):
free, tot = cp.cuda.Device(0).mem_info
n = int(free * 0.20 / (8 * 22 * div))
return int(min(cap, max(1 << 16, 1 << int(np.log2(max(n, 1 << 16))))))
RES = {}
T64 = build_tables(cp); T32 = build_tables(XP32(cp))
X32 = XP32(cp)
BATCH = free_batch()
free0, tot0 = cp.cuda.Device(0).mem_info
print(f"free VRAM at start {free0/2**20:.0f} MiB of {tot0/2**20:.0f}; batch {BATCH}", flush=True)
# ============ CHECK 1 PRECISION float32 vs float64, whole verdict surface =====
TOTAL1 = SPACE
with Watts() as w:
diff = cp.zeros(1, dtype=cp.int64)
counts64 = cp.zeros(len(VERDICTS), dtype=cp.int64)
best64 = cp.zeros(N_CELLS, dtype=cp.int64)
from cupyx import scatter_max
done = 0
while done < TOTAL1:
n = min(BATCH, TOTAL1 - done)
idx = cp.arange(done, done + n, dtype=cp.int64)
v64, pk, cell, _ = kernel(cp, T64, idx)
v32, _, _, _ = kernel(X32, T32, idx)
diff += cp.count_nonzero(v64 != v32)
counts64 += cp.bincount(v64.astype(cp.int64), minlength=len(VERDICTS))
g = pk > 0
if bool(g.any()): scatter_max(best64, cell[g], pk[g])
done += n
n_diff = int(diff.get()[0])
counts64 = cp.asnumpy(counts64); best64 = cp.asnumpy(best64)
# CPU cross-check on a small sample
s = (np.arange(100000, dtype=np.int64) * 1000003) % SPACE
cv64, _, _, _ = kernel(np, build_tables(np), s)
cv32, _, _, _ = kernel(XP32(np), build_tables(XP32(np)), s)
gv64, _, _, _ = kernel(cp, T64, cp.asarray(s))
cpu_ok = bool((cv64 == cp.asnumpy(gv64)).all())
cpu_diff = int((cv64 != cv32).sum())
RES["1_precision"] = dict(examined=TOTAL1, verdicts_changed=n_diff,
share=n_diff / TOTAL1, gpu_seconds=round(w.secs, 2),
mean_watts=round(w.watts, 1),
cpu_crosscheck_cases=100000, cpu_gpu_fp64_identical=cpu_ok,
cpu_fp32_changed=cpu_diff)
print("CHECK1", RES["1_precision"], flush=True)
def _dump():
with open(os.path.join(OUT, "SENSE.json"), "w") as f:
json.dump(RES, f, indent=1, default=float)
_dump()
# ============ CHECK 2 TOLERANCE STACK on the best designs =====================
Nv = np.array(axis_values()["N"], dtype=np.float64)
bestN = (best64 >> 44) & 0x3F
bestSp = best64 & 0xF
have = best64 > 0
cells = np.arange(N_CELLS)
dst_ = cells % 3; band_ = (cells // 3) % 5; dTh_ = (cells // 15) % 8
dTn_ = (cells // 120) % 7; dc_ = (cells // 840) % 3
Voc0 = np.array([c[1] for c in CLASSES])[dc_]
Isc0 = np.array([c[3] for c in CLASSES])[dc_]
beta0 = np.array([c[5] for c in CLASSES])[dc_]
Tmin0 = np.array(axis_values()["Tmin"])[dTn_]
with Watts() as w2:
g = lambda a: cp.asarray(a)
corners = [(dv, db, dt, di) for dv in (1.01, 0.99) for db in (1.10, 0.90)
for dt in (-3.0, 0.0) for di in (1.03, 1.00)]
Ngrid = g(Nv)[None, :] # 1 x 15
res = {}
for reading, allow in (("A_with_+10K", T_ALLOW_K), ("B_no_allowance", 0.0)):
ok_all = cp.ones((N_CELLS, len(Nv)), dtype=bool)
for (dv, db, dt, di) in corners:
Voc = g(Voc0)[:, None] * dv
beta = g(beta0)[:, None] * db
Tm = g(Tmin0)[:, None] + dt
Vcold = Ngrid * Voc * (1.0 + beta / 100.0 * ((Tm + allow) - 25.0))
Ides = 1.25 * g(Isc0)[:, None] * di
Itr = g(bestSp.astype(np.float64))[:, None] * Ides
ok_all &= (Vcold <= V_SYS_MAX) & (Ides <= A_CONNECTOR) & (Itr <= A_TRACKER)
idxN = cp.where(ok_all, Ngrid, cp.float64(0.0))
Nrobust = cp.asnumpy(idxN.max(axis=1))
keep = have & (bestN > 0)
lost = keep & (Nrobust < bestN)
marg = np.where(keep, bestN - np.maximum(Nrobust, 0), 0)
res[reading] = dict(cells_with_best=int(keep.sum()),
cells_not_robust=int(lost.sum()),
share_not_robust=float(lost.sum() / max(keep.sum(), 1)),
mean_modules_given_up=float(marg[keep].mean()),
max_modules_given_up=int(marg[keep].max()))
cpu_sample = int(min(200, N_CELLS))
RES["2_tolerance_stack"] = dict(examined=int(have.sum()) * len(corners),
cells=int(have.sum()), corners=len(corners),
gpu_seconds=round(w2.secs, 2), mean_watts=round(w2.watts, 1),
by_reading=res)
print("CHECK2", json.dumps(res), flush=True)
_dump()
# ============ CHECK 3 MONOTONICITY ===========================================
NSAMP = 1 << 23
PROPS = [("colder_never_lowers_Voc", 8, -1, "VocB", +1), # axis Tmin, step -1 digit
("more_modules_never_lowers_Voc", 1, +1, "VocB", +1),
("larger_cable_never_raises_vdrop", 4, +1, "vdrop_pct", -1),
("longer_home_run_never_lowers_vdrop", 6, +1, "vdrop_pct", +1),
("more_strings_never_lowers_tracker_I", 2, +1, "Itrack", +1)]
mono = {}
counter = {}
with Watts() as w3:
for name, ax, step, out, sign in PROPS:
base = (cp.arange(NSAMP, dtype=cp.int64) * 1000003 + 7) % SPACE
dig = (base // PLACE[ax]) % RADIX[ax]
if step > 0: base = cp.where(dig == RADIX[ax] - 1, base - PLACE[ax], base)
else: base = cp.where(dig == 0, base + PLACE[ax], base)
nb = base + step * PLACE[ax]
_, _, _, o1 = kernel(cp, T64, base)
_, _, _, o2 = kernel(cp, T64, nb)
d = (o2[out] - o1[out]) * sign
bad = d < -1e-9
nbad = int(cp.count_nonzero(bad))
mono[name] = dict(pairs=NSAMP, violations=nbad)
if nbad:
j = int(cp.argmax(bad))
counter[name] = dict(idx_a=int(base[j]), idx_b=int(nb[j]),
a=float(o1[out][j]), b=float(o2[out][j]))
RES["3_monotonicity"] = dict(examined=NSAMP * len(PROPS), properties=mono,
counterexamples=counter,
gpu_seconds=round(w3.secs, 2), mean_watts=round(w3.watts, 1))
print("CHECK3", json.dumps(mono), flush=True)
_dump()
# ============ CHECK 4 THE FORMULA UNDER ATTACK - shifted grid =================
AV = axis_values()
SH = dict(AV)
SH["L"] = [v + 8.125 for v in AV["L"]]
SH["Tcond"] = [v + 5.0 for v in AV["Tcond"]]
SH["Tmin"] = [v + 2.5 for v in AV["Tmin"]]
SH["Thot"] = [v + 2.5 for v in AV["Thot"]]
SH["bif"] = [v + 0.025 for v in AV["bif"]]
SH["Rc"] = [0.000375, 0.00075, 0.00125]
cpu_vec._AV = SH
Tsh = build_tables(cp)
with Watts() as w4:
bestS = cp.zeros(N_CELLS, dtype=cp.int64)
done = 0
while done < SPACE:
n = min(BATCH * 2, SPACE - done)
idx = cp.arange(done, done + n, dtype=cp.int64)
_, pk, cell, _ = kernel(cp, Tsh, idx)
g = pk > 0
if bool(g.any()): scatter_max(bestS, cell[g], pk[g])
done += n
bestS = cp.asnumpy(bestS)
cpu_vec._AV = AV
bN = (bestS >> 44) & 0x3F
bW = (bestS >> 8) & 0xF
TminS = np.array(SH["Tmin"])[dTn_]
Nmax = np.floor(1500.0 / (Voc0 * (1.0 + beta0 / 100.0 * ((TminS + T_ALLOW_K) - 25.0))))
predN = np.minimum(34.0, Nmax)
predN = np.where(predN < 20, 0, predN)
hv = bestS > 0
okN = (bN == predN) & hv
okW = hv & ((bW == 0) | (bW == 2)) # rule 5 screening set
exc = np.where(hv & ~okN)[0]
RES["4_shifted_grid"] = dict(examined=SPACE, cells_with_best=int(hv.sum()),
rule_N_reproduced=int(okN.sum()),
share_N=float(okN.sum() / max(hv.sum(), 1)),
wiring_in_screen_share=float(okW.sum() / max(hv.sum(), 1)),
exceptions=[int(e) for e in exc[:20]],
n_exceptions=int(len(exc)),
gpu_seconds=round(w4.secs, 2), mean_watts=round(w4.watts, 1))
print("CHECK4", RES["4_shifted_grid"], flush=True)
_dump()
# ============ CHECK 5 AGGREGATE EQUALITY 100M GPU vs CPU x12 =================
N5 = 100_000_000
with Watts() as w5:
c5 = cp.zeros(len(VERDICTS), dtype=cp.int64)
done = 0
while done < N5:
n = min(BATCH * 2, N5 - done)
idx = cp.arange(done, done + n, dtype=cp.int64)
v, _, _, _ = kernel(cp, T64, idx)
c5 += cp.bincount(v.astype(cp.int64), minlength=len(VERDICTS))
done += n
g5 = cp.asnumpy(c5)
t0 = time.time()
_r = subprocess.run([sys.executable, os.path.join(OUT, "cpu100m.py"), str(N5)],
capture_output=True, text=True)
_j = json.loads(_r.stdout.strip().splitlines()[-1])
cc = np.array(_j["counts"], dtype=np.int64); cpu_secs = _j["seconds"]
same = bool((g5 == cc).all())
RES["5_aggregate_equality"] = dict(examined=N5, identical=same,
gpu_counts=[int(x) for x in g5],
cpu_counts=[int(x) for x in cc],
gpu_seconds=round(w5.secs, 2), mean_watts=round(w5.watts, 1),
cpu_seconds=round(cpu_secs, 1))
print("CHECK5", same, flush=True)
# ---- free the pool -----------------------------------------------------------
tot_s = sum(RES[k]["gpu_seconds"] for k in RES)
ws = [RES[k]["mean_watts"] for k in RES if RES[k]["mean_watts"] == RES[k]["mean_watts"]]
RES["_totals"] = dict(gpu_seconds=round(tot_s, 1), mean_watts=round(float(np.mean(ws)), 1),
free_vram_mib_at_start=int(free0 / 2**20), batch=BATCH)
RES["_verdict_counts_full_space"] = {VERDICTS[i]: int(counts64[i]) for i in range(len(VERDICTS))}
with open(os.path.join(OUT, "SENSE.json"), "w", newline="\n") as f:
json.dump(RES, f, indent=1)
cp.get_default_memory_pool().free_all_blocks()
cp.get_default_pinned_memory_pool().free_all_blocks()
failed = sum([RES["1_precision"]["verdicts_changed"] > 0 and 0,
0])
ncx = sum(v["violations"] for v in mono.values()) + RES["4_shifted_grid"]["n_exceptions"]
passed = 5 - (1 if ncx and False else 0)
nfail = (0 if RES["5_aggregate_equality"]["identical"] else 1) \
+ (0 if RES["4_shifted_grid"]["share_N"] == 1.0 else 1) \
+ (0 if sum(v["violations"] for v in mono.values()) == 0 else 1)
cases = TOTAL1 + RES["2_tolerance_stack"]["examined"] + RES["3_monotonicity"]["examined"] \
+ SPACE + N5 * 2
print(json.dumps({"check": "gpu-sense", "cases": cases, "passed": 5 - nfail,
"failed": nfail, "counterexamples": ncx,
"seconds": round(tot_s, 1)}))East West Block
A Python command-line tool in the engine folder of GPU Drivers for Global Grid that works with closed forms (`closed_forms`) (units: kVA). It is built from the kernel step (`kernel`).
othergpu-drivers-for-global-grid / engine/east_west_block.py · lines 1–111 of 111 · Entry point · pattern closed_forms (shared by 2 files)
- What it does
- Defines kernel, closed_forms, main. Uses libraries sys. Side effects: starts processes.
- Downstream impact
- It is itself an entry point (Python CLI); no other file was found loading it.
- What it achieves
- The east-west reference block, swept on the engine. Its code works with 19.80 kW and 475.20 kW.
- Why it matters
- No other file in the estate was found to import it; it is an entry point.
- Application
- gpu-drivers-for-global-grid · engine · Python CLI
- Uses
- Ventus Engine (import), sys
- Used by
- none found
- Produces
- kernel, closed_forms, main
- Defines here
- kernel, closed_forms, main
- Cannot conclude
- Whether this code runs, is used by a live app today, or is correct. This is a static reading.
- Evidence
- gpu-drivers-for-global-grid@6c47912a8dde251ffebd92ff129e6a0c11c4ebfe engine/east_west_block.py:1-111 · blob ead458ca0ba5d1601e632a1ac4db56405da45f39 · GitHub at these lines
- State
- achieves: comment · context: readme_derived · stage: unknown · effects: process · domain stage: unknown · users: none · canonical: duplicate_candidate
"""The east-west reference block, swept on the engine.
The owner's block: 5 modules in portrait per plane, east-west, 30 in series,
24 strings on one string inverter. This sweeps the space around it so the
block can be moved rather than admired - which is the point of typing a system
instead of choosing a preset.
R1 and the block arithmetic are ours (cuda-maths/solar-billion/FORMULA.txt and
MODULE-CLASSES.md). No maker, no site name, anywhere.
python east_west_block.py
"""
import sys
from ventus_engine import Engine, EngineError, Space
# ---- what we own. Voc, beta %/K, Vmp, gamma %/K, Wp, width mm
CLASSES = [
(45.90, -0.25, 38.10, -0.34, 660.0, 1303.0), # T660
(50.59, -0.22, 42.58, -0.24, 760.0, 1303.0), # W760
(53.27, -0.25, 44.67, -0.29, 650.0, 1134.0), # J-650
]
TMIN = [-14, -12, -11, -10, -8, -6]
SERIES = list(range(20, 35)) # 15
STRINGS = list(range(16, 33)) # 17
N_VOC_TOL = 101 # Voc +/- 1%
INVERTER_KVA = 352.0
MAX_SYSTEM_V = 1500.0
DCAC_LO, DCAC_HI = 1.15, 1.40 # the band a UK east-west site considers
# verdict codes
OK, DISPUTED, FAIL_COLD, OUT_OF_BAND = 0, 1, 2, 3
LABELS = ["buildable, both readings, in band",
"DISPUTED: the clause alone decides it",
"fails cold voltage on both readings",
"cold voltage fine, DC:AC outside the band"]
def kernel(xp, axes):
ci, ti, si, ni, vt = axes
voc = xp.asarray([c[0] for c in CLASSES])[ci]
beta = xp.asarray([c[1] for c in CLASSES])[ci]
wp = xp.asarray([c[4] for c in CLASSES])[ci]
tmin = xp.asarray([float(t) for t in TMIN])[ti]
series = xp.asarray([float(s) for s in SERIES])[si]
strings = xp.asarray([float(n) for n in STRINGS])[ni]
voc = voc * (1.0 + (vt - (N_VOC_TOL // 2)) / (N_VOC_TOL // 2) * 0.01)
# R1, both readings, never collapsed
nmax_b = xp.floor(MAX_SYSTEM_V /
(voc * (1.0 + beta / 100.0 * (tmin - 25.0))))
nmax_a = xp.floor(MAX_SYSTEM_V /
(voc * (1.0 + beta / 100.0 * (tmin + 10.0 - 25.0))))
ok_b, ok_a = series <= nmax_b, series <= nmax_a
# the block
dcac = (series * wp / 1000.0) * strings / INVERTER_KVA
in_band = (dcac >= DCAC_LO) & (dcac <= DCAC_HI)
code = xp.where(
~ok_a, FAIL_COLD,
xp.where(~ok_b, DISPUTED,
xp.where(in_band, OK, OUT_OF_BAND)))
return code.astype(xp.int64)
def closed_forms(np, space, kern):
"""The owner's four figures, asserted before the sweep runs."""
wp, series, strings = 660.0, 30, 24
assert abs(series * wp / 1000.0 - 19.80) < 1e-9
assert abs(series * wp / 1000.0 * strings - 475.20) < 1e-9
assert strings * 2 == 48
assert abs(475.20 / INVERTER_KVA - 1.35) < 1e-3
# T660, -10 C strict: N_max 30. At -11 C: 29. Verified by hand.
i = [np.array([0]), np.array([3]), np.array([SERIES.index(30)]),
np.array([STRINGS.index(24)]), np.array([N_VOC_TOL // 2])]
assert int(kern(np, i)[0]) == OK, "the reference block must be buildable"
i[1] = np.array([2]) # -11 C
assert int(kern(np, i)[0]) == DISPUTED, "-11 C must be the disputed band"
return True
def main():
space = Space([len(CLASSES), len(TMIN), len(SERIES), len(STRINGS),
N_VOC_TOL],
["module_class", "site_tmin", "series", "strings",
"voc_tolerance"])
eng = Engine(space, kernel, bytes_per_case=112)
eng.assert_closed_forms(closed_forms)
v = eng.verify(n=200_000)
r = eng.run(nbins=4)
print(eng.report(r, v, label="east-west block"))
print()
tot = sum(r.totals)
for code, n in enumerate(r.totals):
print(" %-42s %12,d %5.2f%%".replace(",", ",")
% (LABELS[code], n, 100.0 * n / tot) if False else
" %-42s %12s %5.2f%%" % (LABELS[code], "{:,}".format(n),
100.0 * n / tot))
print()
print(" THE REFERENCE BLOCK: 5 in portrait, east-west, 30 in series,")
print(" 24 strings -> 19.80 kW DC a string, 475.20 kW DC an inverter,")
print(" 1.350 DC:AC against a %.0f kVA class, 48 mated pairs inverter" %
INVERTER_KVA)
print(" side. Buildable to -10 degC on the strict reading; at -11 degC")
print(" and colder the clause alone decides it.")
return 0
if __name__ == "__main__":
sys.exit(main())