Summary: This tutorial demonstrates the implementation of BGE-EN-ICL, a Mistral-7B-based embedding model that supports both zero-shot and few-shot learning. It covers essential techniques for model initialization, custom pooling using [EOS] tokens, and in-context learning implementation using the FlagEmbedding library. The tutorial helps with tasks like generating embeddings for queries and documents, handling attention masks, and setting up few-shot learning with formatted examples. Key features include the model's unique pooling method for unidirectional attention, support for both zero-shot and few-shot scenarios, and flexible example formatting for in-context learning tasks.

# BGE-EN-ICL

In this tutorial, we will go through BGE-EN-ICL, an LLM based embedding model with both strong zero-shot and few-shot embedding capability.

## 0.Installation

Install the required packages in your environment.


```python
%pip install -U transformers FlagEmbedding
```

## 1. BGE-EN-ICL structure


```python
from transformers import AutoTokenizer, AutoModel
import torch, os

tokenizer = AutoTokenizer.from_pretrained("BAAI/bge-en-icl")
raw_model = AutoModel.from_pretrained("BAAI/bge-en-icl")

sentences = ["embedding", "I love machine learning and nlp"]
```

Different from the previous BGE embedding models which are encoder only models, BGE-EN-ICL use decoder only LLM, Mistral-7B, as the base model.


```python
raw_model.eval()
```

## 2. New Pooling Method

BERT-like encoder only networks are considered with strong capacity for representation learning because of their bidirectional attention structure. Some previous work replace unidirectional attention with bidirectional attention during the embedding training phase. But this might creates a mismatch with the model's pre-training design, which could potentially undermine its in-context learning and generative properties.

Thus BGE-EN-ICL introduces a [EOS] token's output embedding to address this issue.


```python
inputs = tokenizer(
    sentences,
    padding=True,
    return_tensors='pt',
)
inputs
```


```python
last_hidden_state = raw_model(**inputs, return_dict=True).last_hidden_state
last_hidden_state.shape
```

The last token/[EOS] pooling method can be described as:

Given the tokenized input sequence $T: [\text{BOS}], t_1, ..., t_N$ is sent into the LLM:
$$h_t = \text{LLM}(T)[\text{EOS}]$$
where $h_t$ represents the text embedding taken from the output embedding of the special token [EOS]


```python
def last_token_pool(last_hidden_states: torch.Tensor,
                    attention_mask: torch.Tensor) -> torch.Tensor:
    
    left_padding = (attention_mask[:, -1].sum() == attention_mask.shape[0])
    if left_padding:
        return last_hidden_states[:, -1]
    else:
        sequence_lengths = attention_mask.sum(dim=1) - 1
        batch_size = last_hidden_states.shape[0]
        return last_hidden_states[torch.arange(batch_size, device=last_hidden_states.device), sequence_lengths]
```


```python
embeddings = last_token_pool(
    last_hidden_state,  
    attention_mask=inputs['attention_mask']
)
embeddings.shape
```

## 3. In-Context Learning

BGE-EN-ICL integrate strong in-context learning of LLM into embedding model while still persisting strong zero-shot embedding capability.

For zero-shot inference, it's exactly same to BGE v1&1.5. For few-shot inference, use the following way:


```python
examples = [
    {
        'instruct': 'Given a web search query, retrieve relevant passages that answer the query.',
        'query': 'what is a virtual interface',
        'response': "A virtual interface is a software-defined abstraction that mimics the behavior and characteristics of a physical network interface. It allows multiple logical network connections to share the same physical network interface, enabling efficient utilization of network resources. Virtual interfaces are commonly used in virtualization technologies such as virtual machines and containers to provide network connectivity without requiring dedicated hardware. They facilitate flexible network configurations and help in isolating network traffic for security and management purposes."
    },
    {
        'instruct': 'Given a web search query, retrieve relevant passages that answer the query.',
        'query': 'causes of back pain in female for a week',
        'response': "Back pain in females lasting a week can stem from various factors. Common causes include muscle strain due to lifting heavy objects or improper posture, spinal issues like herniated discs or osteoporosis, menstrual cramps causing referred pain, urinary tract infections, or pelvic inflammatory disease. Pregnancy-related changes can also contribute. Stress and lack of physical activity may exacerbate symptoms. Proper diagnosis by a healthcare professional is crucial for effective treatment and management."
    }
]

queries = ["how much protein should a female eat", "summit define"]
documents = [
    "As a general guideline, the CDC's average requirement of protein for women ages 19 to 70 is 46 grams per day. But, as you can see from this chart, you'll need to increase that if you're expecting or training for a marathon. Check out the chart below to see how much protein you should be eating each day.",
    "Definition of summit for English Language Learners. : 1  the highest point of a mountain : the top of a mountain. : 2  the highest level. : 3  a meeting or series of meetings between the leaders of two or more governments."
]
```


```python
from FlagEmbedding import FlagICLModel

model = FlagICLModel('BAAI/bge-en-icl', 
                     examples_for_task=examples,  # set `examples_for_task=None` to use model without examples
                     examples_instruction_format="<instruct>{}\n<query>{}\n<response>{}", # specify the format to use examples_for_task
                     devices=[0],
                    )

embeddings_1 = model.encode_queries(queries)
embeddings_2 = model.encode_corpus(documents)
similarity = embeddings_1 @ embeddings_2.T

print(similarity)
```
