PyHDI / veriloggen

Veriloggen: A Mixed-Paradigm Hardware Construction Framework
Apache License 2.0
306 stars 58 forks source link

add stypes.RandXorshift #54

Closed sh-mug closed 1 year ago

sh-mug commented 1 year ago

stypes.RandXorshift

RandXorshift(reg_initval=0x12345678, dependency=None, enable=None, width=32)

Constructor Arguments

The input arguments of stypes.RandXorshift is as the following.

The reset input is intentionally omitted to prevent this function from exhibiting deterministic behavior for large unit operations (e.g., iterations of batch learning).

Implementation

The RandXorshift class implements hardware random number generation using the Xorshift algorithm on embedded systems. The Xorshift algorithm is a pseudo-random number generator that utilizes simple bitwise operations to generate a sequence of seemingly random numbers.

To implement the RandXorshift class, I refer to Marsaglia's paper 'Xorshift RNGs' (2003) and update the values according to the data width, as shown in the pseudo-code below. I treat state variables and outputs only as unsigned integers to ensure accurate Xorshift-based pseudo-random number generation implementation, following the paper's method.

Case for 32-bit data width

uint32_t next(uint32_t x) {
  x ^= (x << 13);
  x ^= (x >> 17);
  x ^= (x << 5);
  return x;
}

Case for 64-bit data width

uint64_t next(uint64_t x) {
  x ^= (x << 13);
  x ^= (x >> 7);
  x ^= (x << 17);
  return x;
}

Test

Referring to the test of stypes.Counter, I added stream_rand_xorshift and verified whether the pseudo-random number sequence output by stypes.RandXorshift matches the expectation.