MCPcopy Create free account
hub / github.com/MegEngine/MegEngine / _multinomial

Function _multinomial

imperative/python/megengine/random/rng.py:213–246  ·  view source on GitHub ↗
(
    input: Tensor, num_samples: int, replacement: bool, seed: int, handle: int
)

Source from the content-addressed store, hash-verified

211
212
213def _multinomial(
214 input: Tensor, num_samples: int, replacement: bool, seed: int, handle: int
215) -> Tensor:
216 handle_cn = None if handle == 0 else _get_rng_handle_compnode(handle)
217 assert num_samples > 0, "Multinomial is not defined when num_samples <= 0"
218 assert (
219 input.ndim == 1 or input.ndim == 2
220 ), "Multinomial is not defined when ndim of input is not 1 or 2"
221 assert input.shape[-1] != 0, "Multinomial is not defined when num of input == 0"
222 assert (
223 input.dtype.name == "float32" or input.dtype.name == "float16"
224 ), "Multinomial is not defined when input dtype is not float"
225 assert (
226 replacement or num_samples <= input.shape[-1]
227 ), "Multinomial is not defined when num_samples > input.shape[-1] in case of no replacement"
228
229 require_one_dim = False
230 if input.ndim == 1:
231 input = input.reshape((1, input.size))
232 require_one_dim = True
233 if replacement:
234 input = input / input.sum(-1, True)
235 assert (
236 handle_cn is None or handle_cn == input.device
237 ), "The input ({}) must be the same device with handle ({})".format(
238 input.device, handle_cn
239 )
240 op = MultinomialRNG(
241 seed=seed, num_samples=num_samples, replacement=replacement, handle=handle
242 )
243 (output,) = apply(op, input)
244 if require_one_dim:
245 output = output.reshape((output.size,))
246 return output
247
248
249def _permutation(n: int, seed: int, device: str, handle: int, dtype: str) -> Tensor:

Callers 1

multinomialMethod · 0.85

Calls 5

MultinomialRNGClass · 0.85
applyFunction · 0.50
reshapeMethod · 0.45
sumMethod · 0.45
formatMethod · 0.45

Tested by

no test coverage detected