File size: 3,695 Bytes
32d1b4a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
"""Persistent one-quality-bit contraction with directional forward derivatives."""
import jax
import jax.numpy as jnp
from jax import lax
from jax.experimental import pallas as pl
from jax.experimental.pallas import triton as plt
from jax._src import core,dispatch
from jax.interpreters import mlir,ad
from jax._src.pallas.triton import lowering
from jax._src.lib.triton import dialect as tt

gather_p=core.Primitive('latent_frontier_vector_gather')
gather_p.def_impl(lambda x,i:dispatch.apply_primitive(gather_p,x,i))
def abstract(x,i):
 assert x.ndim==i.ndim==1 and x.shape==i.shape and i.dtype==jnp.int32
 return core.ShapedArray(x.shape,x.dtype)
gather_p.def_abstract_eval(abstract)
mlir.register_lowering(gather_p,mlir.lower_fun(lambda x,i:x[i],multiple_results=False))
@lowering.register_lowering(gather_p)
def lower(ctx,x,i):return tt.gather(x,i,axis=0)
def gather(x,i):return gather_p.bind(x,i)
def gather_jvp(primals,tangents):
 x,i=primals;dx,_=tangents
 return gather(x,i),jnp.zeros_like(x) if isinstance(dx,ad.Zero) else gather(dx,i)
ad.primitive_jvps[gather_p]=gather_jvp

def physical(t0,t1,t2):
 return .001+.499*jax.nn.sigmoid(t0),.999*jax.nn.sigmoid(t1),.99*jax.nn.sigmoid(t2)

def make_decoder(width=10,interpret=False,derivatives=False,num_warps=8):
 size=1<<(width+1);quality_bit=1<<width
 def decode(theta,dets,probabilities,masks,measured,quality_times,transition_gaps):
  nops,batch=probabilities.shape;directions=3 if derivatives else 1
  def kernel(th,ds,ps,ms,ts,qs,gs,out,jac):
   shot=pl.program_id(0);direction=pl.program_id(1)
   t0=pl.load(th,(0,));t1=pl.load(th,(1,));t2=pl.load(th,(2,))
   unit=tuple((direction==k).astype(jnp.float32) for k in range(3))
   indices=jnp.arange(size,dtype=jnp.int32);quality=(indices&quality_bit)!=0
   def initial(t0,t1,t2):
    pi,_,_=physical(t0,t1,t2)
    return (indices==0)*(1-pi)+(indices==quality_bit)*pi
   if derivatives:f,df=jax.jvp(initial,(t0,t1,t2),unit)
   else:f=initial(t0,t1,t2);df=jnp.zeros_like(f)
   def iteration(op,carry):
    f,df=carry;p=pl.load(ps,(op,shot));mask=pl.load(ms,(op,));detector=pl.load(ts,(op,))
    qt=pl.load(qs,(op,));gap=pl.load(gs,(op,));obs=pl.load(ds,(shot,jnp.maximum(detector,0))).astype(jnp.int32)
    def step(t0,t1,t2,f):
     pi,rho,alpha=physical(t0,t1,t2)
     def transition(f):
      persistence=rho**gap;a=pi*(1-persistence);b=pi+(1-pi)*persistence
      flipped=gather(f,indices^quality_bit)
      return jnp.where(quality,b*f+a*flipped,(1-a)*f+(1-b)*flipped)
     f=lax.cond(gap>0,transition,lambda f:f,f)
     def error(f):
      u=jnp.where(qt>=0,alpha*jnp.minimum(p/pi,(1-p)/(1-pi)),0.)
      rate=p+u*(quality.astype(jnp.float32)-pi)
      return (1-rate)*f+rate*gather(f,indices^mask)
     def project(f):
      g=gather(f,(indices&~mask)|(obs*mask))*((indices&mask)==0)
      return g/jnp.maximum(jnp.sum(g),1e-30)
     return lax.cond(detector<0,error,project,f)
    if derivatives:return jax.jvp(step,(t0,t1,t2,f),(*unit,df))
    return step(t0,t1,t2,f),df
   f,df=lax.fori_loop(0,nops,iteration,(f,df))
   def observable(f):return jnp.sum(jnp.where((indices&1)!=0,f,0))/jnp.maximum(jnp.sum(f),1e-30)
   if derivatives:q,dq=jax.jvp(observable,(f,),(df,))
   else:q=observable(f);dq=jnp.float32(0)
   pl.store(out,(direction,shot),q);pl.store(jac,(direction,shot),dq)
  values=pl.pallas_call(kernel,out_shape=(jax.ShapeDtypeStruct((directions,batch),jnp.float32),jax.ShapeDtypeStruct((directions,batch),jnp.float32)),grid=(batch,directions),interpret=interpret,backend='triton',compiler_params=plt.CompilerParams(num_warps=num_warps,num_stages=1))(
    theta,dets,probabilities,masks,measured,quality_times,transition_gaps)
  return values
 return jax.jit(decode)