readme: ---
  language: "en"
  tags:
  - knowledge-distillation
  datasets:
  - ms_marco
  ---
  
  # Margin-MSE Trained PreTTR
  
  We provide a retrieval trained DistilBert-based PreTTR model (https://arxiv.org/abs/2004.14255). Our model is trained with Margin-MSE using a 3 teacher BERT_Cat (concatenated BERT scoring) ensemble on MSMARCO-Passage.
  
  This instance can be used to **re-rank a candidate set**. The architecture is a 6-layer DistilBERT, split at layer 3, with an additional single linear layer at the end for scoring the CLS token. 
  
  If you want to know more about our simple, yet effective knowledge distillation method for efficient information retrieval models for a variety of student architectures that is used for this model instance check out our paper: https://arxiv.org/abs/2010.02666 🎉
  
  For more information, training data, source code, and a minimal usage example please visit: https://github.com/sebastian-hofstaetter/neural-ranking-kd
  
  ## Configuration
  
  - We split the DistilBERT in half at layer 3
  
  ## Model Code
  
  ````python
  from transformers import DistilBertModel,AutoTokenizer
  from transformers.models.distilbert.modeling_distilbert import *
  import math
  import torch
  from torch import nn as nn
  
  class PreTTRConfig(DistilBertConfig):
      join_layer_idx = 3
  
  class PreTTR(DistilBertModel):
      '''
      PreTTR changes the distilbert model from huggingface to be able to split query and document until a set layer,
      we skipped compression present in the original
  
      from: Efficient Document Re-Ranking for Transformers by Precomputing Term Representations
            MacAvaney, et al. https://arxiv.org/abs/2004.14255
      '''
      config_class = PreTTRConfig
  
      def __init__(self, config):
          super().__init__(config)
          self.transformer = SplitTransformer(config)  # Encoder, we override the classes, but the names stay the same -> so it gets properly initialized
          self.embeddings = PosOffsetEmbeddings(config)  # Embeddings
          self._classification_layer = torch.nn.Linear(self.config.hidden_size, 1, bias=False)
  
          self.join_layer_idx = config.join_layer_idx
  
      def forward(
              self,
              query,
              document,
              use_fp16: bool = False) -> torch.Tensor:
  
          with torch.cuda.amp.autocast(enabled=use_fp16):
  
              query_input_ids = query["input_ids"]
              query_attention_mask = query["attention_mask"]
  
              document_input_ids = document["input_ids"][:, 1:]
              document_attention_mask = document["attention_mask"][:, 1:]
  
              query_embs = self.embeddings(query_input_ids)  # (bs, seq_length, dim)
              document_embs = self.embeddings(document_input_ids, query_input_ids.shape[-1])  # (bs, seq_length, dim)
  
              tfmr_output = self.transformer(
                  query_embs=query_embs,
                  query_mask=query_attention_mask,
                  doc_embs=document_embs,
                  doc_mask=document_attention_mask,
                  join_layer_idx=self.join_layer_idx
              )
              hidden_state = tfmr_output[0]
  
              score = self._classification_layer(hidden_state[:, 0, :]).squeeze()
  
              return score
  
  
  class PosOffsetEmbeddings(nn.Module):
      def __init__(self, config):
          super().__init__()
          self.word_embeddings = nn.Embedding(config.vocab_size, config.dim, padding_idx=config.pad_token_id)
          self.position_embeddings = nn.Embedding(config.max_position_embeddings, config.dim)
          if config.sinusoidal_pos_embds:
              create_sinusoidal_embeddings(
                  n_pos=config.max_position_embeddings, dim=config.dim, out=self.position_embeddings.weight
              )
  
          self.LayerNorm = nn.LayerNorm(config.dim, eps=1e-12)
          self.dropout = nn.Dropout(config.dropout)
  
      def forward(self, input_ids, pos_offset=0):
          """
          Parameters
          ----------
          input_ids: torch.tensor(bs, max_seq_length)
              The token ids to embed.
  
          Outputs
          -------
          embeddings: torch.tensor(bs, max_seq_length, dim)
              The embedded tokens (plus position embeddings, no token_type embeddings)
          """
          seq_length = input_ids.size(1)
          position_ids = torch.arange(seq_length, dtype=torch.long, device=input_ids.device)  # (max_seq_length)
          position_ids = position_ids.unsqueeze(0).expand_as(input_ids) + pos_offset  # (bs, max_seq_length)
  
          word_embeddings = self.word_embeddings(input_ids)  # (bs, max_seq_length, dim)
          position_embeddings = self.position_embeddings(position_ids)  # (bs, max_seq_length, dim)
  
          embeddings = word_embeddings + position_embeddings  # (bs, max_seq_length, dim)
          embeddings = self.LayerNorm(embeddings)  # (bs, max_seq_length, dim)
          embeddings = self.dropout(embeddings)  # (bs, max_seq_length, dim)
          return embeddings
  
  
  class SplitTransformer(nn.Module):
      def __init__(self, config):
          super().__init__()
          self.n_layers = config.n_layers
  
     