You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@tvm.apache.org by GitBox <gi...@apache.org> on 2021/01/06 00:01:53 UTC

[GitHub] [tvm] tkonolige commented on a change in pull request #7083: [RELAY,TOPI] Threefry PRNG: splittable and stateless

tkonolige commented on a change in pull request #7083:
URL: https://github.com/apache/tvm/pull/7083#discussion_r552271978



##########
File path: python/tvm/topi/random/kernel.py
##########
@@ -0,0 +1,407 @@
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements.  See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership.  The ASF licenses this file
+# to you under the Apache License, Version 2.0 (the
+# "License"); you may not use this file except in compliance
+# with the License.  You may obtain a copy of the License at
+#
+#   http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing,
+# software distributed under the License is distributed on an
+# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+# KIND, either express or implied.  See the License for the
+# specific language governing permissions and limitations
+# under the License.
+"""Pseudorandom number kernels."""
+import tvm
+import tvm.topi
+from ... import tir
+from ...tir import ir_builder
+
+
+# Threefry PRNG with splitting based on
+# - J. K. Salmon, M. A. Moraes, R. O. Dror and D. E. Shaw, "Parallel random numbers: As easy as 1,
+#   2, 3," SC '11: Proceedings of 2011 International Conference for High Performance Computing,
+#   Networking, Storage and Analysis, Seattle, WA, 2011, pp. 1-12, doi: 10.1145/2063384.2063405.
+# - Claessen, K. ; Palka, M. (2013) "Splittable Pseudorandom Number Generators using Cryptographic
+#   Hashing". Proceedings of Haskell Symposium 2013 pp. 47-58.  MLA
+# - Ferguson, Niels, et al. "The Skein hash function family." Submission to NIST (round 3) 7.7.5
+#   (2010): 3.
+
+
+# Threefry is a counter based PRNG: given a unique input, it generates a unique random number. As
+# there is no state to maintain, we can apply it to a sequence of numbers (0..N) to generate a
+# sequence of random numbers in parallel. In order to make the PRNG splittable (that is we can
+# generate a sequence of random numbers in one place, and another sequence in another), we add a
+# path and key in addition to the counter. The path allows us to encode a sequence of splits (a 0 in
+# the path indicates the left result of a split, a 1 indicates the right). To avoid continuously
+# growing the path, we can compress an existing path into the key portion of the generator by
+# hashing the current key, path, and counter to create the new key (this same technique is used if
+# we run out of room for the counter).
+
+# This module use encoding e4 from the appendix of "Splittable Pseudorandom Number Generators using
+# Cryptographic Hashing" (confusingly, the definition in the paper uses e3 to define the encoding
+# function). This encoding uses a 10 element uint64 tensor where each byte means the following:
+
+# .. code-block:
+
+#     gen:
+#     words: 0 1 2 3 | 4 5  | 6 7     | 8 9
+#     usage: key     | path | counter | position of next step in path encoded in binary
+#                                       ex: 0b00010 -> next path entry goes one from the right
+
+# Right now, counter only uses the rightmost word.
+
+# Threefry rotation constants from the Skein paper ("The Skein Hash Function Family"
+# https://www.schneier.com/wp-content/uploads/2015/01/skein.pdf)
+_ROTATIONS = {
+    4: [[14, 16], [52, 57], [23, 40], [5, 37], [25, 33], [46, 12], [58, 22], [32, 32]],
+    8: [
+        [46, 36, 19, 37],
+        [33, 27, 14, 42],
+        [17, 49, 36, 39],
+        [44, 9, 54, 56],
+        [39, 30, 34, 24],
+        [13, 50, 10, 17],
+        [25, 29, 39, 43],
+        [8, 35, 56, 22],
+    ],
+    16: [
+        [24, 13, 8, 47, 8, 17, 22, 37],
+        [38, 19, 10, 55, 49, 18, 23, 52],
+        [33, 4, 51, 13, 34, 41, 59, 17],
+        [5, 20, 48, 41, 47, 28, 16, 25],
+        [41, 9, 37, 31, 12, 47, 44, 30],
+        [16, 34, 56, 51, 4, 53, 42, 41],
+        [31, 44, 47, 46, 19, 42, 44, 25],
+        [9, 48, 35, 52, 23, 31, 37, 20],
+    ],
+}
+
+# Threefry permutation constants from the Skein paper ("The Skein Hash Function Family"
+# https://www.schneier.com/wp-content/uploads/2015/01/skein.pdf)
+_PERMUTATIONS = {
+    4: [0, 3, 2, 1],
+    8: [2, 1, 4, 7, 6, 5, 0, 3],
+    16: [0, 9, 2, 13, 6, 11, 4, 15, 10, 7, 12, 3, 14, 5, 8, 1],
+}
+
+
+def _threefry(
+    irb, key_buf, key_offset, counter_buf, counter_offset, out_buf, out_offset, out_shape
+):
+    """IRBuilder code for running Threefry
+
+    Parameters
+    ----------
+    irb: IRBuilder
+        IRBuilder that this code will be generated for.
+
+    key_buf: BufferVar
+        Buffer to read the key from.
+
+    key_offset: number
+        Threefry will write to :code:`key_buf[key_offset:key_offset+4]`
+
+    counter_buf: BufferVar
+        Buffer to read the counter from.
+
+    counter_offset: number
+        Threefry will write to :code:`counter_buf[counter_offset:counter_offset+4]`
+
+    out_buf: BufferVar
+        Buffer to read the counter from.
+
+    out_offset: number
+        Threefry will write to :code:`out_buf[out_offset:out_offset+4*product(out_shape)]`
+
+    out_shape: number
+        Determines the number of ouput states to generate. :code:`state[i]` will correspond to
+        counter+i.
+    """
+    nrounds = 20
+    nwords = 4
+    iwidth = 64
+    assert nrounds % 4 == 0
+    assert nwords in [4, 8, 16]
+
+    assert key_buf.dtype == "uint64"  # TODO: support 32 bit inputs
+    assert key_buf.dtype == counter_buf.dtype
+
+    def mix(a, b, rotation):
+        x = a + b  # TODO should be wrapping
+        y = x ^ ((b << rotation) | (b >> (iwidth - rotation)))
+        return [x, y]
+
+    # temporary buffer for holding the results of _PERMUTATIONS
+    tmp = irb.allocate(out_buf.dtype, out_shape, name="tmp", scope="global")
+    tmp_offset = 0
+
+    # Initialize entire key. It is composed of the original key with one
+    # element appended. The appended element is the xor of all key words plus a
+    # constant.
+    full_key = irb.allocate("uint64", nwords + 1, name="full_key", scope="global")
+    for i in range(nwords):
+        full_key[i] = key_buf[key_offset + i]
+    # initial key constant, full_key[nwords] is equivalent to k_{N_W} in the Skein paper.
+    full_key[nwords] = tvm.tir.const(0x1BD11BDAA9FC1A22, dtype="uint64")
+    for i in range(nwords):
+        full_key[nwords] ^= key_buf[key_offset + i]  # TODO: wrapping
+
+    # TODO: overwrite counter instead?
+    with irb.for_range(0, out_shape, dtype="uint64", name="i") as i:
+        for j in range(nwords):
+            out_buf[out_offset + i * nwords + j] = counter_buf[counter_offset + j] + i
+
+    def key_schedule(s, i):
+        # Threefry uses no tweak, so the key schedule is simple
+        if i == nwords - 1:
+            return full_key[(s + i) % (nwords + 1)] + tvm.tir.const(s, dtype="uint64")
+        return full_key[(s + i) % (nwords + 1)]
+
+    with irb.for_range(0, out_shape, name="l") as l:  # pylint: disable=invalid-name
+        for i in range(nrounds // 4):
+            for j in range(nwords):
+                out_buf[out_offset + l * nwords + j] += key_schedule(i, j)  # TODO wrapping
+            for k in range(4):
+                for j in range(nwords // 2):
+                    (
+                        out_buf[out_offset + l * nwords + j * 2 + 0],
+                        out_buf[out_offset + l * nwords + j * 2 + 1],
+                    ) = mix(
+                        out_buf[out_offset + l * nwords + j * 2 + 0],
+                        out_buf[out_offset + l * nwords + j * 2 + 1],
+                        _ROTATIONS[nwords][(i * 4 + k) % 8][j],
+                    )
+                for j in range(nwords):
+                    tmp[tmp_offset + l * nwords + j] = out_buf[
+                        out_offset + l * nwords + _PERMUTATIONS[nwords][j]
+                    ]
+                # number of rounds is even, so out always contains the result
+                (out_buf, tmp) = (tmp, out_buf)
+                (out_offset, tmp_offset) = (tmp_offset, out_offset)
+

Review comment:
       The only one that matters is `TODO should be wrapping`. I do not know if TVM guarantees unsigned integer arithmetic to be wrapping (instead of saturating).




----------------------------------------------------------------
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

For queries about this service, please contact Infrastructure at:
users@infra.apache.org