MCPcopy Create free account
hub / github.com/PaddlePaddle/Paddle / MultinomialKernel

Function MultinomialKernel

paddle/phi/kernels/xpu/multinomial_kernel.cc:24–73  ·  view source on GitHub ↗

Source from the content-addressed store, hash-verified

22
23template <typename T, typename Context>
24void MultinomialKernel(const Context& dev_ctx,
25 const DenseTensor& x,
26 const Scalar& num_samples,
27 bool replacement,
28 DenseTensor* out) {
29 auto int_num_samples = num_samples.to<int64_t>();
30 int64_t* out_data = dev_ctx.template Alloc<int64_t>(out);
31 auto in_dims = x.dims();
32 int64_t dim_size = in_dims.size();
33 const int64_t num_categories = in_dims[dim_size - 1];
34 const int64_t num_distributions = dim_size > 1 ? in_dims[dim_size - 2] : 1;
35 int64_t seed = dev_ctx.GetGenerator()->Random64();
36
37 // If replacement is False, it's not a replaceable sample. Every category
38 // can be used only once.
39 if (!replacement) {
40 MultinomialInputChecker<T, Context>(dev_ctx, x, num_samples);
41 }
42
43 xpu::ctx_guard RAII_GUARD(dev_ctx.x_context());
44 const float* in_data = nullptr;
45 if (!std::is_same<T, float>::value) {
46 // multinomial only accept float as input
47 using XPUType = typename XPUTypeTrait<T>::Type;
48 auto numel = x.numel();
49 float* cast_buffer = RAII_GUARD.alloc_l3_or_gm<float>(numel);
50 int r =
51 xpu::cast<XPUType, float>(dev_ctx.x_context(),
52 reinterpret_cast<const XPUType*>(x.data<T>()),
53 cast_buffer,
54 numel);
55 PADDLE_ENFORCE_XDNN_SUCCESS(r, "cast");
56 in_data = cast_buffer;
57 } else {
58 in_data = reinterpret_cast<const float*>(x.data<T>());
59 }
60
61 // int multinomial(Context* xpu_ctx, const T* x, TID* y, int64_t num_samples,
62 // int64_t num_categories, int64_t num_distributions, bool replacement,
63 // int64_t seed);
64 int r = xpu::multinomial<float, int64_t>(dev_ctx.x_context(),
65 in_data,
66 out_data,
67 int_num_samples,
68 num_categories,
69 num_distributions,
70 replacement,
71 seed);
72 PADDLE_ENFORCE_XDNN_SUCCESS(r, "multinomial");
73}
74
75} // namespace phi
76

Callers

nothing calls this directly

Calls 7

to<int64_t>Method · 0.80
Random64Method · 0.80
x_contextMethod · 0.80
dimsMethod · 0.45
sizeMethod · 0.45
GetGeneratorMethod · 0.45
numelMethod · 0.45

Tested by

no test coverage detected