quasirandom.py 7.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216
  1. # mypy: allow-untyped-defs
  2. import torch
  3. class SobolEngine:
  4. r"""
  5. The :class:`torch.quasirandom.SobolEngine` is an engine for generating
  6. (scrambled) Sobol sequences. Sobol sequences are an example of low
  7. discrepancy quasi-random sequences.
  8. This implementation of an engine for Sobol sequences is capable of
  9. sampling sequences up to a maximum dimension of 21201. It uses direction
  10. numbers from https://web.maths.unsw.edu.au/~fkuo/sobol/ obtained using the
  11. search criterion D(6) up to the dimension 21201. This is the recommended
  12. choice by the authors.
  13. References:
  14. - Art B. Owen. Scrambling Sobol and Niederreiter-Xing points.
  15. Journal of Complexity, 14(4):466-489, December 1998.
  16. - I. M. Sobol. The distribution of points in a cube and the accurate
  17. evaluation of integrals.
  18. Zh. Vychisl. Mat. i Mat. Phys., 7:784-802, 1967.
  19. Args:
  20. dimension (Int): The dimensionality of the sequence to be drawn
  21. scramble (bool, optional): Setting this to ``True`` will produce
  22. scrambled Sobol sequences. Scrambling is
  23. capable of producing better Sobol
  24. sequences. Default: ``False``.
  25. seed (Int, optional): This is the seed for the scrambling. The seed
  26. of the random number generator is set to this,
  27. if specified. Otherwise, it uses a random seed.
  28. Default: ``None``
  29. Examples::
  30. >>> # xdoctest: +SKIP("unseeded random state")
  31. >>> soboleng = torch.quasirandom.SobolEngine(dimension=5)
  32. >>> soboleng.draw(3)
  33. tensor([[0.0000, 0.0000, 0.0000, 0.0000, 0.0000],
  34. [0.5000, 0.5000, 0.5000, 0.5000, 0.5000],
  35. [0.7500, 0.2500, 0.2500, 0.2500, 0.7500]])
  36. """
  37. MAXBIT = 30
  38. MAXDIM = 21201
  39. def __init__(self, dimension, scramble=False, seed=None):
  40. if dimension > self.MAXDIM or dimension < 1:
  41. raise ValueError(
  42. "Supported range of dimensionality "
  43. f"for SobolEngine is [1, {self.MAXDIM}]"
  44. )
  45. self.seed = seed
  46. self.scramble = scramble
  47. self.dimension = dimension
  48. cpu = torch.device("cpu")
  49. self.sobolstate = torch.zeros(
  50. dimension, self.MAXBIT, device=cpu, dtype=torch.long
  51. )
  52. torch._sobol_engine_initialize_state_(self.sobolstate, self.dimension)
  53. if not self.scramble:
  54. self.shift = torch.zeros(self.dimension, device=cpu, dtype=torch.long)
  55. else:
  56. self._scramble()
  57. self.quasi = self.shift.clone(memory_format=torch.contiguous_format)
  58. self._first_point = (self.quasi / 2**self.MAXBIT).reshape(1, -1)
  59. self.num_generated = 0
  60. def draw(
  61. self,
  62. n: int = 1,
  63. out: torch.Tensor | None = None,
  64. dtype: torch.dtype | None = None,
  65. ) -> torch.Tensor:
  66. r"""
  67. Function to draw a sequence of :attr:`n` points from a Sobol sequence.
  68. Note that the samples are dependent on the previous samples. The size
  69. of the result is :math:`(n, dimension)`.
  70. Args:
  71. n (Int, optional): The length of sequence of points to draw.
  72. Default: 1
  73. out (Tensor, optional): The output tensor
  74. dtype (:class:`torch.dtype`, optional): the desired data type of the
  75. returned tensor.
  76. Default: ``None``
  77. """
  78. if dtype is None:
  79. dtype = torch.get_default_dtype()
  80. if self.num_generated == 0:
  81. if n == 1:
  82. result = self._first_point.to(dtype)
  83. else:
  84. result, self.quasi = torch._sobol_engine_draw(
  85. self.quasi,
  86. n - 1,
  87. self.sobolstate,
  88. self.dimension,
  89. self.num_generated,
  90. dtype=dtype,
  91. )
  92. result = torch.cat((self._first_point.to(dtype), result), dim=-2)
  93. else:
  94. result, self.quasi = torch._sobol_engine_draw(
  95. self.quasi,
  96. n,
  97. self.sobolstate,
  98. self.dimension,
  99. self.num_generated - 1,
  100. dtype=dtype,
  101. )
  102. self.num_generated += n
  103. if out is not None:
  104. out.resize_as_(result).copy_(result)
  105. return out
  106. return result
  107. def draw_base2(
  108. self,
  109. m: int,
  110. out: torch.Tensor | None = None,
  111. dtype: torch.dtype | None = None,
  112. ) -> torch.Tensor:
  113. r"""
  114. Function to draw a sequence of :attr:`2**m` points from a Sobol sequence.
  115. Note that the samples are dependent on the previous samples. The size
  116. of the result is :math:`(2**m, dimension)`.
  117. Args:
  118. m (Int): The (base2) exponent of the number of points to draw.
  119. out (Tensor, optional): The output tensor
  120. dtype (:class:`torch.dtype`, optional): the desired data type of the
  121. returned tensor.
  122. Default: ``None``
  123. """
  124. n = 2**m
  125. total_n = self.num_generated + n
  126. if not (total_n & (total_n - 1) == 0):
  127. raise ValueError(
  128. "The balance properties of Sobol' points require "
  129. f"n to be a power of 2. {self.num_generated} points have been "
  130. f"previously generated, then: n={self.num_generated}+2**{m}={total_n}. "
  131. "If you still want to do this, please use "
  132. "'SobolEngine.draw()' instead."
  133. )
  134. return self.draw(n=n, out=out, dtype=dtype)
  135. def reset(self):
  136. r"""
  137. Function to reset the ``SobolEngine`` to base state.
  138. """
  139. self.quasi.copy_(self.shift)
  140. self.num_generated = 0
  141. return self
  142. def fast_forward(self, n):
  143. r"""
  144. Function to fast-forward the state of the ``SobolEngine`` by
  145. :attr:`n` steps. This is equivalent to drawing :attr:`n` samples
  146. without using the samples.
  147. Args:
  148. n (Int): The number of steps to fast-forward by.
  149. """
  150. if self.num_generated == 0:
  151. torch._sobol_engine_ff_(
  152. self.quasi, n - 1, self.sobolstate, self.dimension, self.num_generated
  153. )
  154. else:
  155. torch._sobol_engine_ff_(
  156. self.quasi, n, self.sobolstate, self.dimension, self.num_generated - 1
  157. )
  158. self.num_generated += n
  159. return self
  160. def _scramble(self):
  161. g: torch.Generator | None = None
  162. if self.seed is not None:
  163. g = torch.Generator()
  164. g.manual_seed(self.seed)
  165. cpu = torch.device("cpu")
  166. # Generate shift vector
  167. shift_ints = torch.randint(
  168. 2, (self.dimension, self.MAXBIT), device=cpu, generator=g
  169. )
  170. self.shift = torch.mv(
  171. shift_ints, torch.pow(2, torch.arange(0, self.MAXBIT, device=cpu))
  172. )
  173. # Generate lower triangular matrices (stacked across dimensions)
  174. ltm_dims = (self.dimension, self.MAXBIT, self.MAXBIT)
  175. ltm = torch.randint(2, ltm_dims, device=cpu, generator=g).tril()
  176. torch._sobol_engine_scramble_(self.sobolstate, ltm, self.dimension)
  177. def __repr__(self):
  178. fmt_string = [f"dimension={self.dimension}"]
  179. if self.scramble:
  180. fmt_string += ["scramble=True"]
  181. if self.seed is not None:
  182. fmt_string += [f"seed={self.seed}"]
  183. return self.__class__.__name__ + "(" + ", ".join(fmt_string) + ")"