Message Boards Message Boards

[?] Compile and infer the rank of tensor correctly?

Posted 7 years ago

In one of my projects, I encountered the following weird behavior of Compile:

In[94]:= Compile[{{r, _Integer}}, 
  Module[{gst = Total@RandomVariate[GammaDistribution[3, 1], r]}, 
   gst]][5]
Out[94]= 12.8387

In[93]:= Compile[{{r, _Integer}}, 
  Module[{gs = RandomVariate[GammaDistribution[3, 1], r]}, 
   Total@gs]][5]
During evaluation of In[93]:= CompiledFunction::cfse: Compiled expression {2.77053,4.99208,2.51185,1.84878,2.6716} should be a machine-size real number.
During evaluation of In[93]:= CompiledFunction::cfex: Could not complete external evaluation at instruction 2; proceeding with uncompiled evaluation.
Out[93]= 14.6549

In[92]:= Compile[{{r, _Integer}}, 
  Module[{gs = RandomVariate[NormalDistribution[3, 1], r]}, 
   Total@gs]][5]
Out[92]= 14.2334

It seems that the rank of RandomVariate[NormalDistribution[x,y],l] can be properly inferred, but not for GammaDistribution.

Thanks in advance!

POSTED BY: Jinxu Zhao
4 Replies
Posted 7 years ago

Thank you so much for the link and your quick reply!

POSTED BY: Jinxu Zhao

See: Which Distributions can be Compiled using RandomVariate

And for a list of the Heads of Compilable functions execute

Sort[Compile`CompilerFunctions[]]

(Note that some argument froms of the heads may not be compilable as you saw from the GammaDistributions)

POSTED BY: David Reiss

This is because the normal distribution is compilable (it's been programmed explicitly into the list of Compilable functions) whereas the Gamma distribution has not. You can see this by comparing at the InputForms of the byt-code compiled expressions.

Normal Distribution:

CompiledFunction[{8, 9., 5468}, {_Integer}, {{2, 0, 0}, {3, 0, 0}}, {{1, {2, 0, 2}}, {4, {2, 0, 3}}, {3, {2, 0, 1}}}, {0, 4, 2, 0, 2}, {{34, 0, 2, 0}, {10, 1, 0}, {10, 2, 1}, {42, "RandomNormal", 3, 0, 0, 3, 0, 1, 2, 1, 0, 3, 1, 1}, {42, "TotalAll", 3, 1, 1, 2, 0, 3, 3, 0, 0}, {1}}, Function[{r}, Module[{gs = RandomVariate[NormalDistribution[3, 1], r]}, Total[gs]]], Evaluate]

GammaDistribution:

CompiledFunction[{8, 9., 5468}, {_Integer}, {{2, 0, 0}, {2, 0, 3}}, {{1, {2, 0, 2}}, {3, {2, 0, 1}}}, {0, 5, 0, 0, 1}, {{34, 0, 2, 0}, {46, Function[{r}, RandomVariate[GammaDistribution[3, 1], r]], 2, 0, 0, 2, 0, 4}, {47, Total, 2, 0, 4, 2, 0, 3}, {1}}, Function[{r}, Module[{gs = RandomVariate[GammaDistribution[3, 1], r]}, Total[gs]]], Evaluate]

Note the explicit Function[{r}, RandomVariate[GammaDistribution[3, 1], r] in the byte code part of Compile

POSTED BY: David Reiss
Posted 7 years ago

Thanks for your reply!

But why some of them are not compilable? e.g. Does it imply that these functions are implemented differently? And how they differ?

POSTED BY: Jinxu Zhao
Reply to this discussion
Community posts can be styled and formatted using the Markdown syntax.
Reply Preview
Attachments
Remove
or Discard

Group Abstract Group Abstract