From 8b2b413db772d7acef35369120c2b56686b0a07e Mon Sep 17 00:00:00 2001 From: Jiri Pittner Date: Thu, 26 Nov 2026 20:08:15 +0100 Subject: [PATCH] initial implementation of hash and checksum --- doc/concepts.tex | 36 ++++++++++++++++++++++++++++++++++++ doc/mat.tex | 1 + doc/smat.tex | 1 + doc/utilities.tex | 3 +++ doc/vec.tex | 1 + la_traits.h | 22 ++++++++++++++++++++++ mat.h | 32 ++++++++++++++++++++++++++++++++ miscfunc.cc | 24 ++++++++++++++++++++++++ miscfunc.h | 37 +++++++++++++++++++++++++++++++++++++ smat.h | 20 ++++++++++++++++++++ t.cc | 32 ++++++++++++++++++++++++++++++++ vec.h | 19 +++++++++++++++++++ 12 files changed, 228 insertions(+) diff --git a/doc/concepts.tex b/doc/concepts.tex index f24b425..822e995 100644 --- a/doc/concepts.tex +++ b/doc/concepts.tex @@ -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} and for \code{NRMat >}} +\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} for \code{NRVec > >}, whereas \code{elementtype} of this object is \code{NRMat >}} \lafunc{typedef ... realtype; typedef ... complextype}{the corresponding real and complex type, e.g.\ \code{NRVec} and \code{NRVec >}} \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::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. diff --git a/doc/mat.tex b/doc/mat.tex index ce2ffd9..078618e 100644 --- a/doc/mat.tex +++ b/doc/mat.tex @@ -206,6 +206,7 @@ Note that scalar addition and subtraction act on the \emph{diagonal} only, i.e.\ \lafunc{const typename LA_traits::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 rsum() const; const NRVec 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::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::normtype nonsymmetry() const}{$\sum_{i>j}|A_{ij}-A_{ji}|^2$ (square of the norm, no square root).} \lafunc{const typename LA_traits::normtype nonhermiticity() const}{Complex types only: $\sum_{i\ge j}|A_{ij}-A_{ji}^*|^2$.} diff --git a/doc/smat.tex b/doc/smat.tex index 556e9d2..a2b15fe 100644 --- a/doc/smat.tex +++ b/doc/smat.tex @@ -166,6 +166,7 @@ generated from the in-place ones. \lafunc{const typename LA_traits::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::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 rsum() const; const NRVec 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 &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}).} diff --git a/doc/utilities.tex b/doc/utilities.tex index 9e4c5b0..da882c9 100644 --- a/doc/utilities.tex +++ b/doc/utilities.tex @@ -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} %===================================================================== diff --git a/doc/vec.tex b/doc/vec.tex index 40d11b0..42f6cb4 100644 --- a/doc/vec.tex +++ b/doc/vec.tex @@ -204,6 +204,7 @@ $|\mathrm{Re}|+|\mathrm{Im}|$). Only \code{double} and \code{std::complex::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::normtype> abs() const}{Vector of $|x_i|$.} diff --git a/la_traits.h b/la_traits.h index 0bbe37a..1319fc5 100644 --- a/la_traits.h +++ b/la_traits.h @@ -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 producttype; typedef C normtype; typedef C realtype; typedef std::complex complextype; +typedef std::complex scalartype; //see the note at the traits of the non-scalar classes +static inline uint64_t hash(const std::complex *x, size_t n, uint64_t h) {return hash_bytes(x,n*sizeof(std::complex),h);} +static inline std::complex checksum(const std::complex &x, uint64_t weight) {return x*(C)checksum_weight(weight);} static inline C sqrabs(const std::complex x) { return x.real()*x.real()+x.imag()*x.imag();} static inline bool gencmp(const std::complex *x, const std::complex *y, size_t n) {return memcmp(x,y,n*sizeof(std::complex));} static bool bigger(const std::complex &x, const std::complex &y) {laerror("std::complex comparison undefined"); return false;} @@ -322,6 +326,13 @@ typedef C producttype; typedef C normtype; typedef C realtype; typedef std::complex 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::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 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, which +//for nested objects is again a class (NRMat for NRVec >); scalartype is the type of the numbers +//at the bottom of the nesting (double in this example, std::complex for NRVec > >); +//it is defined recursively like normtype, which is the corresponding real type + #define generate_traits_nonscalar(X) \ template \ struct LA_traits_aux, scalar_false> { \ @@ -389,8 +405,11 @@ typedef C PAIRTYPE[2]; \ typedef C QUADRUPLETYPE[4]; \ typedef X SUBMATRIXTYPE; \ typedef typename LA_traits::normtype normtype; \ +typedef typename LA_traits::scalartype scalartype; \ typedef X::realtype> realtype; \ typedef X::complextype> complextype; \ +static uint64_t hash(const X *x, size_t n, uint64_t h) {for(size_t i=0; i &x, uint64_t seed) {return x.checksum(seed);} \ static bool gencmp(const X *x, const X *y, size_t n) {for(size_t i=0; i &x, const X &y) {return x>y;} \ static inline bool smaller(const X &x, const X &y) {return x, scalar_false> { \ typedef C elementtype; \ typedef NRMat producttype; \ typedef typename LA_traits::normtype normtype; \ +typedef typename LA_traits::scalartype scalartype; \ typedef X::realtype> realtype; \ typedef X::complextype> complextype; \ +static uint64_t hash(const X *x, size_t n, uint64_t h) {for(size_t i=0; i &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; iy;} \ static inline bool smaller(const C &x, const C &y) {return x::hash(v[0],(size_t)nn*mm,h); +#else + return LA_traits::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 + const typename LA_traits::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::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::checksum(p[i],hash_mix(i,s)); + return r; + } + //! orthonormalize this matrix void orthonormalize(const bool rowcol, const NRSMat *metric = NULL); diff --git a/miscfunc.cc b/miscfunc.cc index d92edce..211582e 100644 --- a/miscfunc.cc +++ b/miscfunc.cc @@ -20,6 +20,7 @@ #include #include #include +#include #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 diff --git a/miscfunc.h b/miscfunc.h index 7c1ea2d..cd3e7b3 100644 --- a/miscfunc.h +++ b/miscfunc.h @@ -20,6 +20,8 @@ #ifndef _MISCFUNC_H #define _MISCFUNC_H +#include +#include 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 diff --git a/smat.h b/smat.h index 6d2c148..e372916 100644 --- a/smat.h +++ b/smat.h @@ -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::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 + const typename LA_traits::scalartype checksum(const uint64_t seed=0) const + { + NOT_GPU(*this); + const uint64_t s=hash_mix(nn,seed); + typename LA_traits::scalartype r=0; + const size_t n=NN2; + for(size_t i=0; i::checksum(v[i],hash_mix(i,s)); + return r; + } + //! sum all matrix elements const T sum(bool onlytriangle=false) const { diff --git a/t.cc b/t.cc index 964b675..c966b79 100644 --- a/t.cc +++ b/t.cc @@ -4892,6 +4892,38 @@ for(int i=0; i 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())< > z(n*m); +z.randomize(1.); +const complex phase=std::polar(1.,0.7); +cout <<"complex checksum "< s(n); +s.randomize(1.); +NRVec iv(n); +for(int i=0; i::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 + const typename LA_traits::scalartype checksum(const uint64_t seed=0) const + { + NOT_GPU(*this); + const uint64_t s=hash_mix(nn,seed); + typename LA_traits::scalartype r=0; + for(int i=0; i::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;