#!/usr/bin/python3

# Linpack written in python3 / torch, almost everything done on GPU
#
# MJ Rutter Nov 2025
#

import torch
from time import time
import sys

try:
  N=int(sys.argv[1])
except:
  N=2000

eps=2.22e-16
ops=(2.0*N)*N*N/3.0+(2.0*N)*N
acc=torch.device(0)

print("Running Linpack ",N,"x",N," on ",acc,"\n")

# Create NxN array of random numbers -0.5 to 0.5

A_GPU=torch.rand(N,N,dtype=torch.float64,device=acc)-0.5

B_GPU=torch.sum(A_GPU,1)
B_GPU=torch.reshape(B_GPU,(N,1))

na=float(torch.max(torch.abs(A_GPU)))

# Solve. linalg.solve not yet supported

t=time()
LU,P=torch.linalg.lu_factor(A_GPU)
X_GPU=torch.linalg.lu_solve(LU,P,B_GPU)
t=time()-t

# Check on GPU

R_GPU=torch.mm(A_GPU,X_GPU)-B_GPU
Rs=float(torch.max(torch.abs(R_GPU)))
nx=float(torch.max(torch.abs(X_GPU)))

print("Residual is ",Rs)
print("Normalised residual is ",Rs/(N*na*nx*eps))
print("Machine epsilon is ",eps)
print("x[0]-1 is ",float(X_GPU[0])-1)
print("x[n-1]-1 is ",float(X_GPU[N-1])-1)

print("Time is ",t)
print("GFLOPS: ",ops*1e-9/t)
