(vocab_size,
                           d_model=512,
                           d_ff=2048,
                           n_layers=6,
                           n_heads=8,
                           dropout=0.1,
                           max_len=2048,
                           mode='train',
                           ff_activation=tl.Relu,
                           skip_fraction=0.4,
                           eval_skip_fraction='every_other')
return tl.Serial(
      tl.ShiftRight(mode=mode),
      embedder,
      [ConditionedBlock(i) for i in range(n_layers)],
      tl.LayerNorm(),
      tl.Dense(vocab_size),
  )
Returns a LayerDrop Transformer language model.

  Based on Fan, Grave, Joulin 2019, https://arxiv.org/abs/1909.11556 .

  The input to the model is a tensor of tokens. (This model uses only the
  decoder part of the overall Transformer.)

  Args:
    vocab_size: int: vocab size
    d_model: int:  depth of embedding
    d_ff: int: depth of feed-forward layer
    n_layers: int: number of encoder/decoder layers
    n_heads: int: number of attention heads
    dropout: float: dropout rate (how much to drop out)
    max_len: int: maximum symbol length for positional encoding
    mode: str: 'train', 'eval' or 'predict', predict mode is for fast inference
    ff_activation: the non-linearity in feed-forward layer
    skip_fraction: probability of skipping a layer; it can be a single
        probability or a list of probabilities different for each layer
    eval_skip_fraction: probability of skipping a layer during eval; it can be a
        single probability, or a list of probabilities different for each layer,
        or a string "every other" implementing a strategy from original paper

  Returns:
    A Transformer language model as a layer that maps from a tensor of tokens
    to activations over a vocab set.
Returns a LayerDrop Transformer language model.
Returns a LayerDrop Transformer language model .
def LayerDropTransformerLM(vocab_size,
                           d_model=512,
                           d_ff=2048,
                           n_layers=6,
                           n_heads=8,
                           dropout=0.1,
                           max_len=2048,
                           mode='train',
                           ff_activation=tl.Relu,
                           skip_fraction=0.4,
                           eval_skip_fraction='every_other'):
  """Returns a LayerDrop Transformer language model.

  Based on Fan, Grave, Joulin 2019, https://arxiv.org/abs/1909.11556 .

  The input to the model is a tensor of tokens. (This model uses only the
  decoder part of the overall Transformer.)

  Args:
    vocab_size: int: vocab size
    d_model: int:  depth of embedding
    d_ff: int: depth of feed-forward layer
    n_layers: int: number of encoder/decoder layers
    n_heads: int: number of attention heads
    dropout: float: dropout rate (how much to drop out)
    max_len: int: maximum symbol length for positional encoding
    mode: str: 'train', 'eval' or 'predict', predict mode is for fast inference
    ff_activation: the non-linearity in feed-forward layer
    skip_fraction: probability of skipping a layer; it can be a single
        probability or a list of probabilities different for each layer
    eval_skip_fraction: probability of skipping a layer during eval; it can be a
        single probability, or a list of probabilities different for each layer,
        or a string "every other" implementing a strategy from original paper

  Returns:
    A Transformer language model as a layer that maps from a tensor of tokens
    to activations over a vocab set.
  """
  embedder = [
      tl.Embedding(vocab_size, d_model),
      tl.Dropout(rate=dropout, mode=mode),
      tl.PositionalEncoding(max_len=max_len, mode=mode),
  ]

  if not isinstance(skip_fraction, (list, tuple)):
    # If we don't get a list of skip_fractions we use the same skip_fraction
    # for each layer.
    skip_fraction = [skip_fraction for i in range(n_layers)]
  if len(skip_fraction) != n_layers:
    raise ValueError('n_layers ({}) must be equal to len(skip_fraction) ({})'
                     .format(n_layers, len(skip_fraction)))

  if eval_skip_fraction == 'every_other':
    # 100% skipping for even-numbered layers; 0% for odd-numbered layers.
    eval_skip_fraction = [(1.0 if i % int(1./skip_fraction[i]) == 0 else 0.0)
                          if skip_fraction[i] != 0 else 0.0
                          for i in range(n_layers)]
  if eval_skip_fraction == 'same':
    # Same skip_fraction as in training.
    eval_skip_fraction = skip_fraction
  if not isinstance(eval_skip_fraction, (list, tuple)):
    # If we don't get a list of eval_skip_fractions we use the same
    # eval_skip_fraction for each layer.
    eval_skip_fraction = [eval_skip_fraction for i in range(n_layers)]
  if len(eval_skip_fraction) != n_layers:
    raise ValueError(
        'n_layers ({}) must be equal to len(eval_skip_fraction) ({})'
        .format(n_layers, len(eval_skip_fraction)))

  @assert_shape('...sd->...sd')
  def ConditionedBlock(current_layer_num):
    return tl.Serial(
        # stack: embedding
        tl.RandomUniform(0., 1, sync=True),
        # stack: random_uniform, embedding
        tl.Cond(
            # if random_uniform > skip_fraction
            LargerThan(skip_fraction[current_layer_num] if mode == 'train'
                       else eval_skip_fraction[current_layer_num]),
            # then: run block
            tl.Serial(transformer._DecoderBlock(  # pylint: disable=g-complex-comprehension,protected-access
                d_model, d_ff, n_heads, dropout, [], mode, ff_activation)),
            # else: run noop
            tl.Serial()
            )
        # stack: embedding
        )

  return tl.Serial(
      tl.ShiftRight(mode=mode),
      embedder,
      [ConditionedBlock(i) for i in range(n_layers)],
      tl.LayerNorm(),
      tl.Dense(vocab_size),
  )
def LayerDropTransformerLM ( vocab_size , d_model = 512 , d_ff = 2048 , n_layers = 6 , n_heads = 8 , dropout = 0.1 , max_len = 2048 , mode = 'train' , ff_activation = tl . Relu , skip_fraction = 0.4 , eval_skip_fraction = 'every_other' ) : embedder = [ tl . Embedding ( vocab_size , d_model ) , tl . Dropout ( rate = dropout , mode = mode ) , tl . PositionalEncoding ( max_len = max_len , mode = mode ) , ] if not isinstance ( skip_fraction , ( list , tuple ) ) : # If we don't get a list of skip_fractions we use the same skip_fraction # for each layer. skip_fraction = [ skip_fraction for i in range ( n_layers ) ] if len ( skip_fraction ) != n_layers : raise ValueError ( 'n_layers ({}) must be equal to len(skip_fraction) ({})' . format ( n_layers , len ( skip_fraction ) ) ) if eval_skip_fraction == 'every_other' : # 100% skipping for even-numbered layers; 0% for odd-numbered layers. eval_skip_fraction = [ ( 1.0 if i % int ( 1. / skip_fraction [ i ] ) == 0 else 0.0 ) if skip_fraction [ i ] != 0 else 0.0 for i in range ( n_layers ) ] if eval_skip_fraction == 'same' : # Same skip_fraction as in training. eval_skip_fraction = skip_fraction if not isinstance ( eval_skip_fraction , ( list , tuple ) ) : # If we don't get a list of eval_skip_fractions we use the same # eval_skip_fraction for each layer. eval_skip_fraction = [ eval_skip_fraction for i in range ( n_layers ) ] if len ( eval_skip_fraction ) != n_layers : raise ValueError ( 'n_layers ({}) must be equal to len(eval_skip_fraction) ({})' . format ( n_layers , len ( eval_skip_fraction ) ) ) @ assert_shape ( '...sd->...sd' ) def ConditionedBlock ( current_layer_num ) : return tl . Serial ( # stack: embedding tl . RandomUniform ( 0. , 1 , sync = True ) , # stack: random_uniform, embedding tl . Cond ( # if random_uniform > skip_fraction LargerThan ( skip_fraction [ current_layer_num ] if mode == 'train' else eval_skip_fraction [ current_layer_num ] ) , # then: run block tl . Serial ( transformer . _DecoderBlock ( # pylint: disable=g-complex-comprehension,protected-access d_model , d_ff , n_heads , dropout , [ ] , mode , ff_activation ) ) , # else: run noop tl . Serial ( ) ) # stack: embedding ) return tl . Serial ( tl . ShiftRight ( mode = mode ) , embedder , [ ConditionedBlock ( i ) for i in range ( n_layers ) ] , tl . LayerNorm ( ) , tl . Dense ( vocab_size ) , )