initial implementation of hash and checksum

This commit is contained in:
jiri committed 2026-11-26 20:08:15 +01:00
1 parent f028a2e0fc
commit 8b2b413db7
12 files changed
+228

No files matched your search

+36
View File
@@ -136,6 +136,7 @@ Its main members are:
\begin{lareference}
\lafunc{typedef ... elementtype}{type of the elements (for a scalar the type itself)}
\lafunc{typedef ... normtype}{type of the norm, e.g.\ \code{double} for \code{std::complex<double>} and for \code{NRMat<std::complex<double> >}}
\lafunc{typedef ... scalartype}{type of the numbers at the bottom of a nested object, defined recursively like \code{normtype} but without taking the real type: \code{std::complex<double>} for \code{NRVec<NRMat<std::complex<double> > >}, whereas \code{elementtype} of this object is \code{NRMat<std::complex<double> >}}
\lafunc{typedef ... realtype; typedef ... complextype}{the corresponding real and complex type, e.g.\ \code{NRVec<double>} and \code{NRVec<std::complex<double> >}}
\lafunc{typedef ... producttype}{type of the product of two objects (for \code{NRSMat} it is \code{NRMat})}
\lafunc{static bool is_plaindata()}{true for scalar types, which can be copied by \code{memcpy}, false for the classes}
@@ -143,6 +144,7 @@ Its main members are:
\lafunc{static normtype norm(const T &x); static void axpy(T &s, const T &x, const elementtype c)}{norm and $s \leftarrow s + c\,x$, used by generic algorithms such as \code{matexp.h}}
\lafunc{static void copyonwrite(T &x); static void clearme(T &x); static void deallocate(T &x)}{generic versions of the member functions (no operation for scalars)}
\lafunc{static void put(int fd, const T &x, ...); static void get(int fd, T &x, ...); multiput; multiget}{binary I/O, recursive for nested types}
\lafunc{static uint64\_t hash(const T *x, size\_t n, uint64\_t h); static scalartype checksum(const T \&x, uint64\_t seed)}{hash and numerical checksum (see below), recursive for nested types}
\lafunc{static T conjugate(const T &x); realpart(x); imagpart(x); setrealpart(x,y); setimagpart(x,y)}{complex helpers, trivial for real types}
\lafunc{static bool bigger(const T &x, const T &y); smaller(x,y)}{comparison used for sorting; for complex types it is an error}
\lafunc{static int strassen_cutoff()}{scalar types only: default \code{cutoff} of \code{NRMat::strassen} (section~\ref{sec:mat:strassen}), currently 2048 for all types}
@@ -302,3 +304,37 @@ void get(int fd, bool dimensions=1, bool transp=0, bool orca_format=false);
\code{NRMat} and the sparse matrices.
\end{description}
For storing many objects of the same size in a scratch file, see \code{AuxStorage} (chapter~\ref{ch:utilities}).
\paragraph{Hash and checksum.} Two functions characterize the contents of an object by one number; they are members of
\code{NRVec}, \code{NRMat} and \code{NRSMat} (and of the classes derived from them) and work for nested objects.
\begin{lstlisting}
uint64_t hash(uint64_t h=LA_HASH_INIT) const;
const typename LA_traits<T>::scalartype checksum(const uint64_t seed=0) const;
\end{lstlisting}
\begin{description}
\item[\code{hash}] is computed from the dimensions and from the exact binary representation of the elements. Two
objects with the same hash are bit by bit the same, up to a negligible chance of a coincidence (64 bits); any
change, however small, gives a completely different value. It is meant for integer data, for keys, and for
checking that a file belongs to the data it was derived from. The argument continues a previous hash, so that
several objects can be combined: \code{h=a.hash(); h=b.hash(h);}. The value depends on the byte order of the
machine, like the binary \code{put} and \code{get}; for floating point data $0$ and $-0$ differ. Plain data are
processed by words of 8 bytes (about 4 GB/s).
\item[\code{checksum}] is the sum of the elements multiplied by fixed pseudorandom weights from $[-1,1)$, which are
determined by the position of the element, the dimensions and the seed. It is a linear function of the
elements over the field of the data: its value is complex for complex data,
$\mathrm{checksum}(\alpha x+y)=\alpha\,\mathrm{checksum}(x)+\mathrm{checksum}(y)$ for objects of the same
dimensions, and a change of the elements by $\delta$ changes it by at most $\sum|\delta|$. It is meant for
floating point data (for integer element types it raises an error) and for comparison within a threshold, which
should be taken relative to the norm of the object, e.g.\ of results obtained on different machines or with
different BLAS libraries. Only objects of the same class and dimensions should be compared (an \code{NRMat} and an
\code{NRSMat} holding the same matrix have different checksums). Objects with different elements have close
checksums only by chance: a difference of the norm $d$ shows as less than $td$ with a probability of about $t$,
which can be made negligible by comparing the checksums for two or three seeds. A NaN among the elements gives NaN.
The cost is about 2~ns per element.
\end{description}
The weights are generated by an own generator without a state (splitmix64 applied to the position and the seed,
\code{hash\_mix} in \code{miscfunc.h}, section~\ref{sec:utilities:miscfunc}); they do not depend on the random number generators of the library, which
the user can replace (section~\ref{sec:utilities:random}), and on the order of any previous calls. Both functions are
frozen: their values are meant to be stored in files and will not change in later versions. The method
\code{checksum} is formally a template, so that traits of user-defined element types need not define
\code{scalartype} unless \code{checksum} is called for them.
+1
View File
@@ -206,6 +206,7 @@ Note that scalar addition and subtraction act on the \emph{diagonal} only, i.e.\
\lafunc{const typename LA_traits<T>::normtype norm(const T scalar = (T)0) const}{Frobenius norm $\|A-s\,\mathbf 1\|_F$ (BLAS \code{nrm2} when $s=0$).}
\lafunc{const T trace() const}{$\sum_i A_{ii}$ (square matrices).}
\lafunc{const T sum() const; const NRVec<T> rsum() const; const NRVec<T> csum() const}{Sum of all elements; vector of row sums (length \code{nrows()}, sum over the column index); vector of column sums (length \code{ncols()}).}
\lafunc{uint64\_t hash(uint64\_t h=LA\_HASH\_INIT) const; const typename LA\_traits<T>::scalartype checksum(const uint64\_t seed=0) const}{Hash of the exact contents and numerical checksum for comparison within a threshold, see section~\ref{sec:concepts:io}.}
\lafunc{inline const T amax() const; inline const T amin() const}{The element (not its index) with the largest resp.\ smallest absolute value; for complex the measure is $|\mathrm{Re}|+|\mathrm{Im}|$ (BLAS \code{i?amax} convention).}
\lafunc{const typename LA_traits<T>::normtype nonsymmetry() const}{$\sum_{i>j}|A_{ij}-A_{ji}|^2$ (square of the norm, no square root).}
\lafunc{const typename LA_traits<T>::normtype nonhermiticity() const}{Complex types only: $\sum_{i\ge j}|A_{ij}-A_{ji}^*|^2$.}
+1
View File
@@ -166,6 +166,7 @@ generated from the in-place ones.
\lafunc{const typename LA_traits<T>::normtype norm(const T scalar = (T)0) const}{Euclidean norm of the packed data of $S - \mathtt{scalar}\cdot 1$; off-diagonal elements are counted \emph{once}, so this is not the Frobenius norm of the full matrix.}
\lafunc{const T trace() const}{Trace.}
\lafunc{const T sum(bool onlytriangle=false) const}{Sum of all elements of the full matrix, or of the stored triangle only.}
\lafunc{uint64\_t hash(uint64\_t h=LA\_HASH\_INIT) const; const typename LA\_traits<T>::scalartype checksum(const uint64\_t seed=0) const}{Hash of the exact contents and numerical checksum for comparison within a threshold, see section~\ref{sec:concepts:io}. Both use the stored triangle only.}
\lafunc{const NRVec<T> rsum() const; const NRVec<T> csum() const}{Row sums and column sums of the full matrix (equal for real, complex conjugate of each other for hermitian matrices).}
\lafunc{inline const T amax() const; inline const T amin() const}{Stored element with the largest/smallest absolute value (complex: $|\Re|+|\Im|$); floating point types only.}
\lafunc{const T* diagonalof(NRVec<T> &r, const bool divide = 0, bool cache = false) const}{\code{divide=false}: store the diagonal into \code{r} and return \code{&r[0]}; \code{divide=true}: divide \code{r} elementwise by the nonzero diagonal elements and return \code{NULL}. \code{cache} is unused. Interface used by iterative solvers (\ref{ch:iterative}).}
+3
View File
@@ -166,6 +166,9 @@ symmetric tensors, chapter~\ref{ch:tensor}). $s(d,n)=0$ for $n\le0$, $1$ for $d=
recurrence $s(d,n)=s(d,n-1)+s(d-1,n)$ into a table growing on demand; \code{laerror} for $d\ge16$ or $n\ge1024$.}
\lafunc{int inverse_simplicial(int d, unsigned long long s)}{Largest $n$ with \code{simplicial(d,n)}${}\le s$ (Newton
iteration on the polynomial $s(d,n)$ followed by an integer correction); 0 for $s=0$. \code{laerror} for $d\ge16$.}
\lafunc{static inline uint64\_t hash\_mix(const uint64\_t counter, const uint64\_t seed)}{Pseudorandom 64-bit number as a fixed function of its arguments (splitmix64); a generator without a state, independent of \code{la\_random.h}. It generates the weights of \code{checksum} and combines the dimensions into \code{hash} (section~\ref{sec:concepts:io}); it must never be changed.}
\lafunc{static inline double checksum\_weight(const uint64\_t z)}{The number \code{z} mapped to $[-1,1)$.}
\lafunc{uint64\_t hash\_bytes(const void *x, const size\_t nbytes, uint64\_t h=LA\_HASH\_INIT)}{Hash of \code{nbytes} bytes of plain data, taken by words of 8 bytes, continuing from \code{h}; used by \code{hash} of the classes for scalar element types. Frozen as well.}
\end{lareference}
%=====================================================================
+1
View File
@@ -204,6 +204,7 @@ $|\mathrm{Re}|+|\mathrm{Im}|$). Only \code{double} and \code{std::complex<double
\lafunc{const T max() const; const T min() const}{Largest / smallest element (0 for an empty vector). Only real types
(instantiated for the integer types, \code{float}, \code{double}).}
\lafunc{const T sum() const}{$\sum_i x_i$.}
\lafunc{uint64\_t hash(uint64\_t h=LA\_HASH\_INIT) const; const typename LA\_traits<T>::scalartype checksum(const uint64\_t seed=0) const}{Hash of the exact contents and numerical checksum for comparison within a threshold, see section~\ref{sec:concepts:io}.}
\lafunc{const T sumsqr() const}{$\sum_i x_i^2$, 0 for an empty vector. No conjugation for complex types; use \code{norm()} for $\sqrt{\sum_i|x_i|^2}$.}
\lafunc{const T prod() const}{$\prod_i x_i$, 1 for an empty vector.}
\lafunc{NRVec<typename LA_traits<T>::normtype> abs() const}{Vector of $|x_i|$.}
+22
View File
@@ -45,6 +45,7 @@
#include "laerror.h"
#include "la_random.h"
#include "miscfunc.h"
#include "cuda_la.h"
@@ -261,6 +262,9 @@ typedef std::complex<C> producttype;
typedef C normtype;
typedef C realtype;
typedef std::complex<C> complextype;
typedef std::complex<C> scalartype; //see the note at the traits of the non-scalar classes
static inline uint64_t hash(const std::complex<C> *x, size_t n, uint64_t h) {return hash_bytes(x,n*sizeof(std::complex<C>),h);}
static inline std::complex<C> checksum(const std::complex<C> &x, uint64_t weight) {return x*(C)checksum_weight(weight);}
static inline C sqrabs(const std::complex<C> x) { return x.real()*x.real()+x.imag()*x.imag();}
static inline bool gencmp(const std::complex<C> *x, const std::complex<C> *y, size_t n) {return memcmp(x,y,n*sizeof(std::complex<C>));}
static bool bigger(const std::complex<C> &x, const std::complex<C> &y) {laerror("std::complex comparison undefined"); return false;}
@@ -322,6 +326,13 @@ typedef C producttype;
typedef C normtype;
typedef C realtype;
typedef std::complex<C> complextype;
typedef C scalartype; //see the note at the traits of the non-scalar classes
static inline uint64_t hash(const C *x, size_t n, uint64_t h) {return hash_bytes(x,n*sizeof(C),h);}
static inline C checksum(const C &x, uint64_t weight)
{
if(std::numeric_limits<C>::is_integer) laerror("checksum() is for floating point types only, use hash()");
return x*(C)checksum_weight(weight);
}
static inline C sqrabs(const C x) { return x*x;}
static inline bool gencmp(const C *x, const C *y, size_t n) {return memcmp(x,y,n*sizeof(C));}
static inline bool bigger(const C &x, const C &y) {return x>y;}
@@ -380,6 +391,11 @@ static int strassen_cutoff() {return 2048;} //NRMat::strassen uses plain gemm fo
template<typename C>
struct LA_traits; //forward declaration needed for template recursion
//NOTE on elementtype and scalartype: elementtype is the type of the elements stored in the object, i.e. C for X<C>, which
//for nested objects is again a class (NRMat<double> for NRVec<NRMat<double> >); scalartype is the type of the numbers
//at the bottom of the nesting (double in this example, std::complex<double> for NRVec<NRMat<std::complex<double> > >);
//it is defined recursively like normtype, which is the corresponding real type
#define generate_traits_nonscalar(X) \
template<typename C> \
struct LA_traits_aux<X<C>, scalar_false> { \
@@ -389,8 +405,11 @@ typedef C PAIRTYPE[2]; \
typedef C QUADRUPLETYPE[4]; \
typedef X<C> SUBMATRIXTYPE; \
typedef typename LA_traits<C>::normtype normtype; \
typedef typename LA_traits<C>::scalartype scalartype; \
typedef X<typename LA_traits<C>::realtype> realtype; \
typedef X<typename LA_traits<C>::complextype> complextype; \
static uint64_t hash(const X<C> *x, size_t n, uint64_t h) {for(size_t i=0; i<n; ++i) h=x[i].hash(h); return h;} \
static scalartype checksum(const X<C> &x, uint64_t seed) {return x.checksum(seed);} \
static bool gencmp(const X<C> *x, const X<C> *y, size_t n) {for(size_t i=0; i<n; ++i) if(x[i]!=y[i]) return true; return false;} \
static inline bool bigger(const X<C> &x, const X<C> &y) {return x>y;} \
static inline bool smaller(const X<C> &x, const X<C> &y) {return x<y;} \
@@ -434,8 +453,11 @@ struct LA_traits_aux<X<C>, scalar_false> { \
typedef C elementtype; \
typedef NRMat<C> producttype; \
typedef typename LA_traits<C>::normtype normtype; \
typedef typename LA_traits<C>::scalartype scalartype; \
typedef X<typename LA_traits<C>::realtype> realtype; \
typedef X<typename LA_traits<C>::complextype> complextype; \
static uint64_t hash(const X<C> *x, size_t n, uint64_t h) {for(size_t i=0; i<n; ++i) h=x[i].hash(h); return h;} \
static scalartype checksum(const X<C> &x, uint64_t seed) {return x.checksum(seed);} \
static bool gencmp(const C *x, const C *y, size_t n) {for(size_t i=0; i<n; ++i) if(x[i]!=y[i]) return true; return false;} \
static inline bool bigger(const C &x, const C &y) {return x>y;} \
static inline bool smaller(const C &x, const C &y) {return x<y;} \
+32
View File
@@ -272,6 +272,38 @@ public:
//! sum all matrix elements
const T sum() const;
//! hash of the dimensions and of the exact binary contents, continuing from h (see miscfunc.h)
uint64_t hash(uint64_t h=LA_HASH_INIT) const
{
NOT_GPU(*this);
h=hash_mix(mm,hash_mix(nn,h));
if(nn==0||mm==0) return h;
#ifdef MATPTR
return LA_traits<T>::hash(v[0],(size_t)nn*mm,h);
#else
return LA_traits<T>::hash(v,(size_t)nn*mm,h);
#endif
}
//! numerical checksum: sum of the elements with pseudorandom weights given by the seed and the dimensions (see miscfunc.h)
//it is a template only in order not to require scalartype in the traits of every type of elements
template<typename U=T>
const typename LA_traits<U>::scalartype checksum(const uint64_t seed=0) const
{
NOT_GPU(*this);
const uint64_t s=hash_mix(mm,hash_mix(nn,seed));
typename LA_traits<U>::scalartype r=0;
if(nn==0||mm==0) return r;
#ifdef MATPTR
const T *p=v[0];
#else
const T *p=v;
#endif
const size_t n=(size_t)nn*mm;
for(size_t i=0; i<n; ++i) r+=LA_traits<U>::checksum(p[i],hash_mix(i,s));
return r;
}
//! orthonormalize this matrix
void orthonormalize(const bool rowcol, const NRSMat<T> *metric = NULL);
+24
View File
@@ -20,6 +20,7 @@
#include <stdint.h>
#include <limits>
#include <math.h>
#include <string.h>
#include "miscfunc.h"
#include "laerror.h"
@@ -474,4 +475,27 @@ return n;
#undef SIMPLICIAL_MAXN
//hash of plain data, see miscfunc.h; never change it, the values are stored in files
uint64_t hash_bytes(const void *x, const size_t nbytes, uint64_t h)
{
const char *p=(const char *)x;
size_t n=nbytes;
uint64_t w;
for(; n>=8; n-=8, p+=8)
{
memcpy(&w,p,8);
h=(h^w)*0x9E3779B97F4A7C15ULL;
h^=h>>32;
}
if(n)
{
w=0;
memcpy(&w,p,n);
h=(h^w)*0x9E3779B97F4A7C15ULL;
h^=h>>32;
}
return hash_mix(nbytes,h);
}
}//namespace
+37
View File
@@ -20,6 +20,8 @@
#ifndef _MISCFUNC_H
#define _MISCFUNC_H
#include <stdint.h>
#include <stddef.h>
namespace LA {
@@ -40,6 +42,41 @@ extern unsigned long long simplicial(int d, int n); //simplicial numbers in a pr
extern int inverse_simplicial(int d, unsigned long long s);
//auxiliary functions for hash() and checksum() of the LA classes
//hash(): 64-bit integer computed from the dimensions and from the exact binary representation of the elements;
//it tells with a negligible chance of a coincidence whether two objects (or an object and what a file was made from)
//are bit by bit the same; it depends on the byte order of the machine like the binary put() and get()
//checksum(): sum of the elements multiplied by fixed pseudorandom weights from [-1,1) which depend on the position of the
//element, on the dimensions and on the seed; it is a linear function of the elements, so that objects which
//differ little have checksums which differ little, and it is to be compared within a threshold (relative to the norm
//of the object) between objects of the same class and dimensions; objects with different elements have close
//checksums only by chance, which can be made less likely by comparing the checksums for several seeds
//NOTE: the functions below must never be changed, since hashes and checksums are meant to be stored in files
//NOTE: the weights come from the own generator hash_mix() and do not depend on RANDDOUBLE etc. (la_random.h), which
//the user can replace by his own random number generators
//starting value of hash()
#define LA_HASH_INIT 0x9E3779B97F4A7C15ULL
//pseudorandom 64-bit number as a fixed function of a counter and a seed (splitmix64); it has no state
static inline uint64_t hash_mix(const uint64_t counter, const uint64_t seed)
{
uint64_t z=seed+(counter+1)*0x9E3779B97F4A7C15ULL;
z=(z^(z>>30))*0xBF58476D1CE4E5B9ULL;
z=(z^(z>>27))*0x94D049BB133111EBULL;
return z^(z>>31);
}
//weight from [-1,1) made of a number from hash_mix()
static inline double checksum_weight(const uint64_t z)
{
return (double)(int64_t)z*(1./9223372036854775808.);
}
//hash of plain data continuing from the value h; the data are taken by words of 8 bytes for speed
extern uint64_t hash_bytes(const void *x, const size_t nbytes, uint64_t h=LA_HASH_INIT);
}//namespace
#endif
+20
View File
@@ -173,6 +173,26 @@ public:
inline const T amax() const;
inline const T amin() const;
//! hash of the dimension and of the exact binary contents of the stored triangle, continuing from h (see miscfunc.h)
uint64_t hash(uint64_t h=LA_HASH_INIT) const
{
NOT_GPU(*this);
return LA_traits<T>::hash(v,NN2,hash_mix(nn,h));
}
//! numerical checksum: sum of the stored elements with pseudorandom weights given by the seed and the dimension (see miscfunc.h)
//it is a template only in order not to require scalartype in the traits of every type of elements
template<typename U=T>
const typename LA_traits<U>::scalartype checksum(const uint64_t seed=0) const
{
NOT_GPU(*this);
const uint64_t s=hash_mix(nn,seed);
typename LA_traits<U>::scalartype r=0;
const size_t n=NN2;
for(size_t i=0; i<n; ++i) r+=LA_traits<U>::checksum(v[i],hash_mix(i,s));
return r;
}
//! sum all matrix elements
const T sum(bool onlytriangle=false) const
{
+32
View File
@@ -4892,6 +4892,38 @@ for(int i=0; i<n; ++i) for(int j=0; j<m; ++j) if(c(j,i)!=a(i,j) || ic(j,i)!=ia(i
cout <<"Dimensions of the plain read "<<c.nrows()<<" "<<c.ncols()<<", number of elements differing from the transposed matrix = "<<err<<endl;
}
if(0) //hash() and checksum(): exact and numerical comparison of the contents
{
int n,m;
cin>>n>>m;
NRMat<double> a(n,m),b;
a.randomize(1.);
b=a;
cout <<"hashes of equal matrices "<<a.hash()<<" "<<b.hash()<<" checksums "<<a.checksum()<<" "<<b.checksum()<<endl;
b.copyonwrite();
b(n/2,m/2)+=1e-10;
cout <<"after a change of one element by 1e-10: hash "<<b.hash()<<" difference of the checksums "<<b.checksum()-a.checksum()<<" for another seed "<<b.checksum(1)-a.checksum(1)<<endl;
NRMat<double> c(n,m);
c.randomize(1.);
cout <<"error of the linearity of the checksum = "<<(a*2.5+c).checksum()-(2.5*a.checksum()+c.checksum())<<endl;
NRVec<complex<double> > z(n*m);
z.randomize(1.);
const complex<double> phase=std::polar(1.,0.7);
cout <<"complex checksum "<<z.checksum()<<" error after a multiplication by a phase = "<<abs((z*phase).checksum()-phase*z.checksum())<<endl;
NRVec<NRVec<NRMat<double> > > nested(2);
nested[0].resize(2);
nested[1].resize(1);
nested[0][0]=a;
nested[0][1]=c;
nested[1][0]=a;
cout <<"nested object: hash "<<nested.hash()<<" checksum "<<nested.checksum()<<endl;
NRSMat<double> s(n);
s.randomize(1.);
NRVec<int> iv(n);
for(int i=0; i<n; ++i) iv[i]=i;
cout <<"symmetric matrix: hash "<<s.hash()<<" checksum "<<s.checksum()<<"; hash of an integer vector chained with it "<<iv.hash(s.hash())<<endl;
}
if(0) //testbed of the general methods
{
int seed;
+19
View File
@@ -393,6 +393,25 @@ public:
//! compute the sum of the vector elements
const T sum() const;
//! hash of the dimension and of the exact binary contents, continuing from h (see miscfunc.h)
uint64_t hash(uint64_t h=LA_HASH_INIT) const
{
NOT_GPU(*this);
return LA_traits<T>::hash(v,nn,hash_mix(nn,h));
}
//! numerical checksum: sum of the elements with pseudorandom weights given by the seed and the dimension (see miscfunc.h)
//it is a template only in order not to require scalartype in the traits of every type of elements
template<typename U=T>
const typename LA_traits<U>::scalartype checksum(const uint64_t seed=0) const
{
NOT_GPU(*this);
const uint64_t s=hash_mix(nn,seed);
typename LA_traits<U>::scalartype r=0;
for(int i=0; i<nn; ++i) r+=LA_traits<U>::checksum(v[i],hash_mix(i,s));
return r;
}
//! compute the sum of squares the vector elements
inline const T sumsqr() const {
if(nn==0) return (T)0;