transformers safetensors endpoints_compatible region:us
---
library_name: transformers
tags: []
---

# Model Card for Model ID

<!-- Provide a quick summary of what the model is/does. -->


In this repositoty we fine tuned Llava [link](https://huggingface.co/llava-hf/llava-v1.6-mistral-7b-hf)

LLaVA (Large Language and Vision Assistant) models are a type of artificial intelligence that combines language understanding with visual perception. These models are designed to process and understand both text and images, allowing them to perform tasks that require interpreting visual information and responding in natural language.

Key features of LLaVA models include:

1. Multimodal capabilities: They can analyze images and respond to questions or prompts about them in natural language.

2. Visual grounding: LLaVA models can connect language concepts to visual elements in images.

3. Task versatility: They can be used for various tasks like visual question answering, image captioning, and visual reasoning.

4. Foundation model integration: LLaVA builds upon large language models, extending their capabilities to include visual understanding.

LLaVA models represent an important step in developing AI systems that can interact with the world more comprehensively, bridging the gap between language and visual perception.

Would you like me to elaborate on any specific aspect of LLaVA models, such as their architecture, training process, or potential applications?

## what do you find in this README?
1. how to use this fine tuned model
2. how I trained the Llave model of the dataset
3. how I tested it locally and pushed it into huggingface



## Dataset

The dataset that we consider to fine tune themodel is [link](https://huggingface.co/datasets/naver-clova-ix/cord-v1)"naver-clova-ix/cord-v1" that you can find it in the dataset huggingface.

# 1. How to use the fine tunned model
```python

from transformers import AutoProcessor, BitsAndBytesConfig, LlavaNextForConditionalGeneration
import torch

import sys
import os

import lightning as L
from torch.utils.data import DataLoader
import re
from nltk import edit_distance
import numpy as np


def setting_directory(depth):
    current_dir = os.path.abspath(os.getcwd())
    root_dir = current_dir
    for i in range(depth):
        root_dir = os.path.abspath(os.path.join(root_dir, os.pardir))
        sys.path.append(os.path.dirname(root_dir))
    return root_dir

root_dir = setting_directory(1)
epochs = 100


model_name = "Ali-Forootani/llava-v1.6-mistral-7b-hf_100epochs_fine_tune"
processor = AutoProcessor.from_pretrained(model_name)
model = LlavaNextForConditionalGeneration.from_pretrained(model_name)

device = torch.device("cuda" if torch.cuda.is_available() else "cpu")

model.eval()
model = model.to(device)



from datasets import load_dataset
dataset = load_dataset("naver-clova-ix/cord-v2")

#You can save the model in the local directory as well
dataset.save_to_disk("/data/bio-eng-llm/llm_repo/naver-clova-ix/cord-v2")

test_example = dataset["test"][3]
test_image = test_example["image"]

MAX_LENGTH = 256  # or any other suitable value
#prepare image and prompt for the model
#To do this can be replaced by apply_chat_template when the processor supports this
prompt = f"[INST] <image>\nExtract JSON [\INST]"
inputs = processor(text=prompt, images=[test_image], return_tensors="pt").to("cuda")
for k,v in inputs.items():
    print(k,v.shape)

# Generate token IDs
generated_ids = model.generate(**inputs, max_new_tokens=MAX_LENGTH)

# Decode back into text
generated_texts = processor.batch_decode(generated_ids, skip_special_tokens=True)

print(generated_texts)


#######################################
####################################### You can make the output nicer



import re

# let's turn that into JSON
def token2json(tokens, is_inner_value=False, added_vocab=None):
        """
        Convert a (generated) token sequence into an ordered JSON format.
        """
        if added_vocab is None:
            added_vocab = processor.tokenizer.get_added_vocab()

        output = {}

        while tokens:
            start_token = re.search(r"<s_(.*?)>", tokens, re.IGNORECASE)
            if start_token is None:
                break
            key = start_token.group(1)
            key_escaped = re.escape(key)

            end_token = re.search(rf"</s_{key_escaped}>", tokens, re.IGNORECASE)
            start_token = start_token.group()
            if end_token is None:
                tokens = tokens.replace(start_token, "")
            else:
                end_token = end_token.group()
                start_token_escaped = re.escape(start_token)
                end_token_escaped = re.escape(end_token)
                content = re.search(
                    f"{start_token_escaped}(.*?){end_token_escaped}", tokens, re.IGNORECASE | re.DOTALL
                )
                if content is not None:
                    content = content.group(1).strip()
                    if r"<s_" in content and r"</s_" in content:  # non-leaf node
                        value = token2json(content, is_inner_value=True, added_vocab=added_vocab)
                        if value:
                            if len(value) == 1:
                                value = value[0]
                            output[key] = value
                    else:  # leaf nodes
                        output[key] = []
                        for leaf in content.split(r"<sep/>"):
                            leaf = leaf.strip()
                            if leaf in added_vocab and leaf[0] == "<" and leaf[-2:] == "/>":
                                leaf = leaf[1:-2]  # for categorical special tokens
                            output[key].append(leaf)
                        if len(output[key]) == 1:
                            output[key] = output[key][0]

                tokens = tokens[tokens.find(end_token) + len(end_token) :].strip()
                if tokens[:6] == r"<sep/>":  # non-leaf nodes
                    return [output] + token2json(tokens[6:], is_inner_value=True, added_vocab=added_vocab)

        if len(output):
            return [output] if is_inner_value else output
        else:
            return [] if is_inner_value else {"text_sequence": tokens}
        


generated_json = token2json(generated_texts[0])
print(generated_json)

for key, value in generated_json.items():
    print(key, value)

```


# 2. How to fine-tune LLaVa for document parsing (PDF -> JSON)

In this notebook, we are going to fine-tune the [LLaVa](https://huggingface.co/docs/transformers/main/en/model_doc/llava) model for a document AI use case. LLaVa is one of the better open-source multimodal models at the time of writing (there's already a successor called [LLaVa-NeXT](https://huggingface.co/docs/transformers/main/en/model_doc/llava_next)). As we'll see, fine-tuning these various models is pretty similar as their API is mostly the same.

The goal for the model in this notebook is to generate a JSON that contains key fields (like food items and their corresponding prices) from receipts. We will fine-tune LLaVa on the [CORD](https://huggingface.co/datasets/naver-clova-ix/cord-v2) dataset, which contains (receipt image, ground truth JSON) pairs.

Sources:

* LLaVa [documentation](https://huggingface.co/docs/transformers/main/en/model_doc/llava)
* LLaVa [models on the hub](https://huggingface.co/llava-hf)


## Define variables and importing moduls

We'll first set some variables useful througout this tutorial.


```python

from transformers import AutoProcessor, BitsAndBytesConfig, LlavaNextForConditionalGeneration
from peft import LoraConfig, prepare_model_for_kbit_training, get_peft_model

import torch
import sys
import os

import lightning as L
from torch.utils.data import DataLoader
import re
from nltk import edit_distance
import numpy as np

# if you would like to set the directory you can use this piece of code
def setting_directory(depth):
    current_dir = os.path.abspath(os.getcwd())
    root_dir = current_dir
    for i in range(depth):
        root_dir = os.path.abspath(os.path.join(root_dir, os.pardir))
        sys.path.append(os.path.dirname(root_dir))
    return root_dir

root_dir = setting_directory(1)
epochs = 100




import lightning as L
from torch.utils.data import DataLoader
import re
from nltk import edit_distance
import numpy as np

##############################


MAX_LENGTH = 256

# MODEL_ID = "llava-hf/llava-v1.6-mistral-7b-hf"

MODEL_ID = "/data/bio-eng-llm/llm_repo/llava-hf/llava-v1.6-mistral-7b-hf"
REPO_ID = "YOUR-HUB-REPO-TO-PUSH"
WANDB_PROJECT = "LLaVaNeXT"
WANDB_NAME = "llava-next-demo-cord"
```


## Load dataset

Let's start by loading the dataset from the hub. Here we use the [CORD](https://huggingface.co/datasets/naver-clova-ix/cord-v2) dataset, created by the [Donut](https://huggingface.co/docs/transformers/en/model_doc/donut) authors (Donut is another powerful - but slightly undertrained document AI model available in the Transformers library). CORD is an important benchmark for receipt understanding. The Donut authors have prepared it in a format that suits vision-language models: we're going to fine-tune it to generate the JSON given the image.

If you want to load your own custom dataset, check out this guide: https://huggingface.co/docs/datasets/image_dataset.


```python
from datasets import load_dataset
dataset = load_dataset("naver-clova-ix/cord-v2")

#see one image as an example
example = dataset['train'][0]
image = example["image"]
# resize image for smaller displaying
width, height = image.size
image = image.resize((int(0.3*width), int(0.3*height)))
print(image)
```


## Load processor

Next, we'll load the processor which is used to prepare the data in the format that the model expects. Neural networks like LLaVa don't directly take images and text as input, but rather `pixel_values` (which is a resized, rescaled, normalized and optionally splitted version of the receipt images), `input_ids` (which are text token indices in the vocabulary of the model), etc. This is handled by the processor.

### Image resolution

The image resolution at which multimodal models are trained greatly has an impact on performance. One of the shortcomings of LLaVa is that it uses a fairly low image resolution (336x336). Newer models like LLaVa-NeXT and Idefics2 use a much higher image resolution enabling the model to "see" a lot more details in the image (which improves its OCR performance among other things). On the other hand, using a bigger image resolution comes at a cost of much higher memory requirements and longer training times. This is less of an issue with LLaVa due to its relatively small image resolution.

## Load model

Next, we're going to load the LLaVa model from the [hub](https://huggingface.co/llava-hf/llava-1.5-7b-hf). This is a model with about 7 billion trainable parameters (as it combines a LLaMa-7B language model with a relatively low-parameter vision encoder). Do note that we load a model here which already has undergone supervised fine-tuning (SFT) on the [LLaVa-Instruct-150K](https://huggingface.co/datasets/liuhaotian/LLaVA-Instruct-150K) instruction dataset. We can benefit from the fine-tuning that the model already has undergone.

### Full fine-tuning, LoRa and Q-LoRa

As this model has 7 billion trainable parameters, that's going to have quite an impact on the amount of memory used. For reference, fine-tuning a model using the [AdamW optimizer](https://pytorch.org/docs/stable/generated/torch.optim.AdamW.html#torch.optim.AdamW) (which is often used to optimize neural networks) with mixed precision, you need about 18 times the amount of parameters in GB of GPU RAM. So in this case, we would need 18x7 billion bytes = 126 GB of GPU RAM if we want to update all the parameters of the model!! That's huge right? And for most people infeasible.

Luckily, some clever people came up with the [LoRa](https://huggingface.co/docs/peft/main/en/conceptual_guides/lora) method (LoRa is short for low-rank adapation). It allows to just freeze the existing weights and only train a couple of adapter layers on top of the base model. Hugging Face offers the separate [PEFT library](https://huggingface.co/docs/peft/main/en/index) for easy use of LoRa, along with other Parameter-Efficient Fine-Tuning methods (that's where the name PEFT comes from).

Moreover, one can not only freeze the existing base model but also quantize it (which means, shrinking down its size). A neural network's parameters are typically saved in either float32 (which means, 32 bits or 4 bytes are used to store each parameter value) or float16 (which means, 16 bits or half a byte - also called half precision). However, with some clever algorithms one can shrink each parameter to just 8 or 4 bits (half a byte!), without significant effect on final performance. Read all about it here: https://huggingface.co/blog/4bit-transformers-bitsandbytes.

This means that we're going to shrink the size of the base Idefics2-8b model considerably using 4-bit quantization, and then only train a couple of adapter layers on top using LoRa (in float16). This idea of combining LoRa with quantization is called Q-LoRa and is the most memory friendly version.

Of course, if you have the memory available, feel free to use full fine-tuning or LoRa without quantization! In case of full fine-tuning, the code snippet below instantiates the model with Flash Attention which considerably speeds up computations.

There exist many forms of quantization, here we leverage the [BitsAndBytes](https://huggingface.co/docs/transformers/main_classes/quantization#transformers.BitsAndBytesConfig) integration.


```python

from transformers import BitsAndBytesConfig, LlavaNextForConditionalGeneration
import torch

USE_LORA = False
USE_QLORA = True


device = torch.device("cuda" if torch.cuda.is_available() else "cpu")


## Load model

# Three options for training, from the lowest precision training to the highest precision training:
# - QLora
# - Standard Lora
# - Full fine-tuning
if USE_QLORA or USE_LORA:
    if USE_QLORA:
        bnb_config = BitsAndBytesConfig(
            load_in_4bit= True, bnb_4bit_quant_type="nf4", bnb_4bit_compute_dtype=torch.float16, device = device,
        )
    model = LlavaNextForConditionalGeneration.from_pretrained(
        MODEL_ID,
        torch_dtype=torch.float16,
        quantization_config=bnb_config,
    )
else:
    # for full fine-tuning, we can speed up the model using Flash Attention
    # only available on certain devices, see https://github.com/Dao-AILab/flash-attention?tab=readme-ov-file#installation-and-features
    model = LlavaNextForConditionalGeneration.from_pretrained(
        MODEL_ID,
        torch_dtype=torch.float16,
        _attn_implementation="flash_attention_2",
    )

```

## Apply PEFT

After loading the base model, we're going to add LoRa adapter layers. We're going to only train these adapter layers (the base model is kept frozen).

The difference here with other models are the layers at which we're going to add adapters (in PEFT this is called `target_modules`). This typically depends a bit on the model.

Here, I based myself off the original `find_all_linear_names` [function](https://github.com/haotian-liu/LLaVA/blob/ec3a32ddea47d8739cb6523fb2661b635c15827e/llava/train/train.py#L169) found in the original LLaVa repository. It means that we're going to add adapters to all linear layers of the model (`nn.Linear`), except for the ones present in the vision encoder and multimodal projector.
This means that we're mostly going to adapt the language model part of LLaVa for our use case.


```python
from peft import LoraConfig, prepare_model_for_kbit_training, get_peft_model


def find_all_linear_names(model):
    cls = torch.nn.Linear
    lora_module_names = set()
    multimodal_keywords = ['multi_modal_projector', 'vision_model']
    for name, module in model.named_modules():
        if any(mm_keyword in name for mm_keyword in multimodal_keywords):
            continue
        if isinstance(module, cls):
            names = name.split('.')
            lora_module_names.add(names[0] if len(names) == 1 else names[-1])

    if 'lm_head' in lora_module_names: # needed for 16-bit
        lora_module_names.remove('lm_head')
    return list(lora_module_names)


lora_config = LoraConfig(
    r=8,
    lora_alpha=8,
    lora_dropout=0.1,
    target_modules=find_all_linear_names(model),
    init_lora_weights="gaussian",
)

model = prepare_model_for_kbit_training(model)
model = get_peft_model(model, lora_config)
```

## Create PyTorch dataset

Next we'll create a regular [PyTorch dataset](https://pytorch.org/tutorials/beginner/basics/data_tutorial.html) which defines the individual items of the dataset. For that, one needs to implement 3 methods: an `init` method, a `len` method (which returns the length of the dataset) and a `getitem` method (which returns items of the dataset).

The `init` method goes over all the ground truth JSON sequences and turns them into token sequences (which we want the model to generate) using the `json2token` method. Unlike in my Donut and Idefics2 notebooks, we're not going to add special tokens to the model's vocabulary to omit complexity. Feel free to check them out, I haven't ablated whether adding special tokens gives a big boost in performance.

Typically, one uses the processor in the `getitem` method to prepare the data in the format that the model expects, but we'll postpone that here for a reason we'll explain later. In our case we're just going to return 2 things: the image and a corresponding ground truth token sequence.




```python
from torch.utils.data import Dataset
from typing import Any, Dict
import random

class LlavaDataset(Dataset):
    """
    PyTorch Dataset for LLaVa. This class takes a HuggingFace Dataset as input.

    Each row, consists of image path(png/jpg/jpeg) and ground truth data (json/jsonl/txt).
    """

    def __init__(
        self,
        dataset_name_or_path: str,
        split: str = "train",
        sort_json_key: bool = True,
    ):
        super().__init__()

        self.split = split
        self.sort_json_key = sort_json_key

        self.dataset = load_dataset(dataset_name_or_path, split=self.split)
        self.dataset_length = len(self.dataset)

        self.gt_token_sequences = []
        for sample in self.dataset:
            ground_truth = json.loads(sample["ground_truth"])
            if "gt_parses" in ground_truth:  # when multiple ground truths are available, e.g., docvqa
                assert isinstance(ground_truth["gt_parses"], list)
                gt_jsons = ground_truth["gt_parses"]
            else:
                assert "gt_parse" in ground_truth and isinstance(ground_truth["gt_parse"], dict)
                gt_jsons = [ground_truth["gt_parse"]]

            self.gt_token_sequences.append(
                [
                    self.json2token(
                        gt_json,
                        sort_json_key=self.sort_json_key,
                    )
                    for gt_json in gt_jsons  # load json from list of json
                ]
            )

    def json2token(self, obj: Any, sort_json_key: bool = True):
        """
        Convert an ordered JSON object into a token sequence
        """
        if type(obj) == dict:
            if len(obj) == 1 and "text_sequence" in obj:
                return obj["text_sequence"]
            else:
                output = ""
                if sort_json_key:
                    keys = sorted(obj.keys(), reverse=True)
                else:
                    keys = obj.keys()
                for k in keys:
                    output += (
                        fr"<s_{k}>"
                        + self.json2token(obj[k], sort_json_key)
                        + fr"</s_{k}>"
                    )
                return output
        elif type(obj) == list:
            return r"<sep/>".join(
                [self.json2token(item, sort_json_key) for item in obj]
            )
        else:
            obj = str(obj)
            return obj

    def __len__(self) -> int:
        return self.dataset_length

    def __getitem__(self, idx: int) -> Dict:
        """
        Returns one item of the dataset.

        Returns:
            image : the original Receipt image
            target_sequence : tokenized ground truth sequence
        """
        sample = self.dataset[idx]

        # inputs
        image = sample["image"]
        target_sequence = random.choice(self.gt_token_sequences[idx])  # can be more than one, e.g., DocVQA Task 1

        return image, target_sequence

########################################

##################### If you want to choose a few number of dataset!  ##################
class LlavaDataset2(Dataset):
    """
    PyTorch Dataset for LLaVa. This class takes a HuggingFace Dataset as input.

    Each row, consists of image path(png/jpg/jpeg) and ground truth data (json/jsonl/txt).
    """

    def __init__(
        self,
        dataset_name_or_path: str,
        split: str = "train",
        sort_json_key: bool = True,
        num_samples: int = None
    ):
        super().__init__()

        self.split = split
        self.sort_json_key = sort_json_key

        self.dataset = load_dataset(dataset_name_or_path, split=self.split)
        self.dataset_length = len(self.dataset)

        # If num_samples is specified and is less than the dataset length, select a subset
        if num_samples is not None and num_samples < self.dataset_length:
            indices = random.sample(range(self.dataset_length), num_samples)
            self.dataset = self.dataset.select(indices)
            self.dataset_length = num_samples

        self.gt_token_sequences = []
        for sample in self.dataset:
            ground_truth = json.loads(sample["ground_truth"])
            if "gt_parses" in ground_truth:  # when multiple ground truths are available, e.g., docvqa
                assert isinstance(ground_truth["gt_parses"], list)
                gt_jsons = ground_truth["gt_parses"]
            else:
                assert "gt_parse" in ground_truth and isinstance(ground_truth["gt_parse"], dict)
                gt_jsons = [ground_truth["gt_parse"]]

            self.gt_token_sequences.append(
                [
                    self.json2token(
                        gt_json,
                        sort_json_key=self.sort_json_key,
                    )
                    for gt_json in gt_jsons  # load json from list of json
                ]
            )

    def json2token(self, obj: Any, sort_json_key: bool = True):
        """
        Convert an ordered JSON object into a token sequence
        """
        if isinstance(obj, dict):
            if len(obj) == 1 and "text_sequence" in obj:
                return obj["text_sequence"]
            else:
                output = ""
                keys = sorted(obj.keys(), reverse=True) if sort_json_key else obj.keys()
                for k in keys:
                    output += (
                        fr"<s_{k}>"
                        + self.json2token(obj[k], sort_json_key)
                        + fr"</s_{k}>"
                    )
                return output
        elif isinstance(obj, list):
            return r"<sep/>".join(
                [self.json2token(item, sort_json_key) for item in obj]
            )
        else:
            return str(obj)

    def __len__(self) -> int:
        return self.dataset_length

    def __getitem__(self, idx: int) -> Dict:
        """
        Returns one item of the dataset.

        Returns:
            image : the original Receipt image
            target_sequence : tokenized ground truth sequence
        """
        sample = self.dataset[idx]

        # inputs
        image = sample["image"]
        target_sequence = random.choice(self.gt_token_sequences[idx])  # can be more than one, e.g., DocVQA Task 1

        return image, target_sequence



train_dataset = LlavaDataset2("naver-clova-ix/cord-v2",  split="train",
                                sort_json_key=False,
                                num_samples=100
                                )

val_dataset = LlavaDataset2("naver-clova-ix/cord-v2", split="validation",
                            sort_json_key=False,
                            num_samples=100
                            )

########################################



train_dataset = LlavaDataset("naver-clova-ix/cord-v2",  split="train", sort_json_key=False)
val_dataset = LlavaDataset("naver-clova-ix/cord-v2", split="validation", sort_json_key=False)



train_example = train_dataset[0]
image, target_sequence = train_example
print(target_sequence)
```


## Define collate functions

Now that we have PyTorch datasets, we'll define a so-called collators which define how items of the dataset should be batched together. This is because we typically train neural networks on batches of data (i.e. various images/target sequences combined) rather than one-by-one, using a variant of stochastic-gradient descent or SGD (like Adam, AdamW, etc.).

It's only here that we're going to use the processor to turn the (image, target token sequence) into the format that the model expects (which is `pixel_values`, `input_ids` etc.). The reason we do that here is because it allows for **dynamic padding** of the batches: each batch contains ground truth sequences of varying lengths. By only using the processor here, we will pad the `input_ids` up to the largest sequence in the batch.

We also decide to limit the length of the text tokens (`input_ids`) to a max length due to memory constraints, feel free to expand if your target token sequences are longer (I'd recommend plotting the average token length of your dataset to determine the optimal value).

The formatting of the `input_ids` is super important: we need to respect a so-called [chat template](https://huggingface.co/docs/transformers/main/en/chat_templating). As of now, LLaVa does not yet support chat templates, so we manually write down the prompt in the correct format (which starts with USER and ends with ASSISTANT). I'll update my notebook when it is supported. We use the text prompt "Extract JSON", this is just a deliberate choice, you could also omit this and just train the model on (image, JSON) pairs without text prompt.

Labels are created for the model by simply copying the inputs to the LLM (`input_ids`), but with padding tokens replaced by the ignore index of the loss function. This ensures that the model doesn't need to learn to predict padding tokens (used to batch examples together).

Why are the labels a copy of the model inputs, you may ask? The model will internally shift the labels one position to the right so that the model will learn to predict the next token. This can be seen [here](https://github.com/huggingface/transformers/blob/6f465d45d98f9eaeef83cfdfe79aecc7193b0f1f/src/transformers/models/idefics2/modeling_idefics2.py#L1851-L1855).

The collate function for evaluation is different, since there we only need to feed the prompt to the model, as we'll use the `generate()` method to autoregressively generate a completion.




```python
def train_collate_fn(examples):
    images = []
    texts = []
    for example in examples:
        image, ground_truth = example
        images.append(image)
        # TODO: in the future we can replace this by processor.apply_chat_template
        prompt = f"[INST] <image>\nExtract JSON [\INST] {ground_truth}"
        texts.append(prompt)

    batch = processor(text=texts, images=images, padding=True, truncation=True, max_length=MAX_LENGTH, return_tensors="pt")

    labels = batch["input_ids"].clone()
    labels[labels == processor.tokenizer.pad_token_id] = -100
    batch["labels"] = labels

    input_ids = batch["input_ids"]
    attention_mask = batch["attention_mask"]
    pixel_values = batch["pixel_values"]
    image_sizes = batch["image_sizes"]
    labels = batch["labels"]

    return input_ids, attention_mask, pixel_values, image_sizes, labels


def eval_collate_fn(examples):
    # we only feed the prompt to the model
    images = []
    texts = []
    answers = []
    for example in examples:
        image, ground_truth = example
        images.append(image)
        # TODO: in the future we can replace this by processor.apply_chat_template
        prompt = f"[INST] <image>\nExtract JSON [\INST]"
        texts.append(prompt)
        answers.append(ground_truth)

    batch = processor(text=texts, images=images, return_tensors="pt", padding=True)

    input_ids = batch["input_ids"]
    attention_mask = batch["attention_mask"]
    pixel_values = batch["pixel_values"]
    image_sizes = batch["image_sizes"]

    return input_ids, attention_mask, pixel_values, image_sizes, answers
```

## Define PyTorch LightningModule

There are various ways to train a PyTorch model: one could just use native PyTorch, use the [Trainer API](https://huggingface.co/docs/transformers/en/main_classes/trainer) or frameworks like [Accelerate](https://huggingface.co/docs/accelerate/en/index). In this notebook, I'll use PyTorch Lightning as it allows to easily compute evaluation metrics during training.

Below, we define a [LightningModule](https://lightning.ai/docs/pytorch/stable/common/lightning_module.html), which is the standard way to train a model in PyTorch Lightning. A LightningModule is an `nn.Module` with some additional functionality.

Basically, PyTorch Lightning will take care of all device placements (`.to(device)`) for us, as well as the backward pass, putting the model in training mode, etc.

Notice the difference between a training step and an evaluation step:

- a training step only consists of a forward pass, in which we compute the cross-entropy loss between the model's next token predictions and the ground truth (in parallel for all tokens, this technique is known as "teacher forcing"). The backward pass is handled by PyTorch Lightning.
- an evaluation step consists of making the model autoregressively complete the prompt using the [`generate()`](https://huggingface.co/docs/transformers/v4.40.1/en/main_classes/text_generation#transformers.GenerationMixin.generate) method. After that, we compute an evaluation metric between the predicted sequences and the ground truth ones. This allows us to see how the model is improving over the course of training. The metric we use here is the so-called [Levenhstein edit distance](https://en.wikipedia.org/wiki/Levenshtein_distance). This quantifies how much we would need to edit the predicted token sequence to get the target sequence (the fewer edits the better!). Its optimal value is 0 (which means, no edits need to be made).

Besides that, we define the optimizer to use ([AdamW](https://pytorch.org/docs/stable/generated/torch.optim.AdamW.html) is a good default choice) and the data loaders, which use the collate functions defined above to batch together items of the PyTorch datasets. Do note that AdamW is a pretty heavy optimizer in terms of memory requirements, but as we're training with QLoRa we only need to store optimizer states for the adapter layers. For full fine-tuning, one could take a look at more memory friendly optimizers such as [8-bit Adam](https://huggingface.co/docs/bitsandbytes/main/en/optimizers).


```python
import lightning as L
from torch.utils.data import DataLoader
import re
from nltk import edit_distance
import numpy as np


class LlavaModelPLModule(L.LightningModule):
    def __init__(self, config, processor, model):
        super().__init__()
        self.config = config
        self.processor = processor
        self.model = model

        self.batch_size = config.get("batch_size")

    def training_step(self, batch, batch_idx):

        input_ids, attention_mask, pixel_values, image_sizes, labels = batch

        outputs = self.model(input_ids=input_ids,
                            attention_mask=attention_mask,
                            pixel_values=pixel_values,
                            image_sizes=image_sizes,
                            labels=labels
                          )
        loss = outputs.loss

        self.log("train_loss", loss)

        return loss

    def validation_step(self, batch, batch_idx, dataset_idx=0):

        input_ids, attention_mask, pixel_values, image_sizes, answers = batch

        # autoregressively generate token IDs
        generated_ids = self.model.generate(input_ids=input_ids, attention_mask=attention_mask,
                                       pixel_values=pixel_values, image_sizes=image_sizes, max_new_tokens=MAX_LENGTH)
        # turn them back into text, chopping of the prompt
        # important: we don't skip special tokens here, because we want to see them in the output
        predictions = self.processor.batch_decode(generated_ids[:, input_ids.size(1):], skip_special_tokens=True)

        scores = []
        for pred, answer in zip(predictions, answers):
            pred = re.sub(r"(?:(?<=>) | (?=</s_))", "", pred)
            scores.append(edit_distance(pred, answer) / max(len(pred), len(answer)))

            if self.config.get("verbose", False) and len(scores) == 1:
                print(f"Prediction: {pred}")
                print(f"    Answer: {answer}")
                print(f" Normed ED: {scores[0]}")

        self.log("val_edit_distance", np.mean(scores))

        return scores

    def configure_optimizers(self):
        # you could also add a learning rate scheduler if you want
        optimizer = torch.optim.AdamW(self.parameters(), lr=self.config.get("lr"))

        return optimizer

    def train_dataloader(self):
        return DataLoader(train_dataset, collate_fn=train_collate_fn, batch_size=self.batch_size, shuffle=True, num_workers=4)

    def val_dataloader(self):
        return DataLoader(val_dataset, collate_fn=eval_collate_fn, batch_size=self.batch_size, shuffle=False, num_workers=4)


epochs = 100


config = {"max_epochs": epochs ,
          # "val_check_interval": 0.2, # how many times we want to validate during an epoch
          "check_val_every_n_epoch": 1,
          "gradient_clip_val": 1.0,
          "accumulate_grad_batches": 8,
          "lr": 1e-4,
          "batch_size": 1,
          # "seed":2022,
          "num_nodes": 1,
          "warmup_steps": 50,
          "result_path": "./result",
          "verbose": True,
}

model_module = LlavaModelPLModule(config, processor, model)
```

## Define callbacks

Optionally, Lightning allows to define so-called [callbacks](https://lightning.ai/docs/pytorch/stable/extensions/callbacks.html), which are arbitrary pieces of code that can be executed during training.

Here I'm adding a `PushToHubCallback` which will push the model to the [hub](https://huggingface.co/) at the end of every epoch as well as at the end of training. Do note that you could of course also pass the `private=True` flag when pushing to the hub, if you wish to keep your model private. Hugging Face also offers the [Enterprise Hub](https://huggingface.co/enterprise) so that you can easily share models with your colleagues privately in a secure way.

We'll also use the EarlyStopping callback of Lightning, which will automatically stop training once the evaluation metric (edit distance in our case) doesn't improve after 3 epochs.


```python
from lightning.pytorch.callbacks import Callback
from lightning.pytorch.callbacks.early_stopping import EarlyStopping

from huggingface_hub import HfApi

api = HfApi()

class PushToHubCallback(Callback):
    def on_train_epoch_end(self, trainer, pl_module):
        print(f"Pushing model to the hub, epoch {trainer.current_epoch}")
        pl_module.model.push_to_hub(REPO_ID,
                                    commit_message=f"Training in progress, epoch {trainer.current_epoch}")

    def on_train_end(self, trainer, pl_module):
        print(f"Pushing model to the hub after training")
        pl_module.processor.push_to_hub(REPO_ID,
                                    commit_message=f"Training done")
        pl_module.model.push_to_hub(REPO_ID,
                                    commit_message=f"Training done")

early_stop_callback = EarlyStopping(monitor="val_edit_distance", patience=3, verbose=False, mode="min")
```

## Train!

Alright, we're set to start training! We will also pass the Weights and Biases logger so that we get see some pretty plots of our loss and evaluation metric during training (do note that you may need to log in the first time you run this, see the [docs](https://docs.wandb.ai/guides/integrations/lightning)).

Do note that this Trainer class supports many more flags! See the docs: https://lightning.ai/docs/pytorch/stable/api/lightning.pytorch.trainer.trainer.Trainer.html#lightning.pytorch.trainer.trainer.Trainer.


_hint_: you may track the training on wandb, but first you should create an account and login! then use it! I did not use it so I commented in the code!
```bash
pip install -U wandb>=0.12.10
```

```python
trainer = L.Trainer(
        accelerator="gpu",
        devices=[0],
        max_epochs=config.get("max_epochs"),
        accumulate_grad_batches=config.get("accumulate_grad_batches"),
        check_val_every_n_epoch=config.get("check_val_every_n_epoch"),
        gradient_clip_val=config.get("gradient_clip_val"),
        precision="16-mixed",
        limit_val_batches=5,
        num_sanity_val_steps=0,
        logger=None,
        #callbacks=[PushToHubCallback(), early_stop_callback],
)

trainer.fit(model_module)



##############################################
 
# You can save the model in your local directory as you wish
save_dir = root_dir + f"models/fine_tuned_models/llava-v1.6-mistral-7b-hf_{epochs}e_qa_qa"
#trainer.save_model(save_dir)

trainer.save_checkpoint(f"{save_dir}/checkpoint.ckpt")

print("Saved model to:", save_dir)

```
# 3. How to test the model locally by loading the saved checkpoint:

```python

from transformers import AutoProcessor, BitsAndBytesConfig, LlavaNextForConditionalGeneration
import torch

import sys
import os

import lightning as L
from torch.utils.data import DataLoader
import re
from nltk import edit_distance
import numpy as np


def setting_directory(depth):
    current_dir = os.path.abspath(os.getcwd())
    root_dir = current_dir
    for i in range(depth):
        root_dir = os.path.abspath(os.path.join(root_dir, os.pardir))
        sys.path.append(os.path.dirname(root_dir))
    return root_dir

root_dir = setting_directory(1)
epochs = 100




import lightning as L
from torch.utils.data import DataLoader
import re
from nltk import edit_distance
import numpy as np

##############################


MAX_LENGTH = 256

# MODEL_ID = "llava-hf/llava-v1.6-mistral-7b-hf"

MODEL_ID = "/data/bio-eng-llm/llm_repo/llava-hf/llava-v1.6-mistral-7b-hf"
REPO_ID = "YOUR-HUB-REPO-TO-PUSH"
WANDB_PROJECT = "LLaVaNeXT"
WANDB_NAME = "llava-next-demo-cord"


from transformers import AutoProcessor

processor = AutoProcessor.from_pretrained(MODEL_ID)
processor.tokenizer.padding_side = "right" # during training, one always uses padding on the right

from transformers import BitsAndBytesConfig, LlavaNextForConditionalGeneration
import torch

   
from peft import LoraConfig, prepare_model_for_kbit_training, get_peft_model


USE_LORA = False
USE_QLORA = True


device = torch.device("cuda" if torch.cuda.is_available() else "cpu")


## Load model

# Three options for training, from the lowest precision training to the highest precision training:
# - QLora
# - Standard Lora
# - Full fine-tuning
if USE_QLORA or USE_LORA:
    if USE_QLORA:
        bnb_config = BitsAndBytesConfig(
            load_in_4bit= True, bnb_4bit_quant_type="nf4", bnb_4bit_compute_dtype=torch.float16, device = device,
        )
    model = LlavaNextForConditionalGeneration.from_pretrained(
        MODEL_ID,
        torch_dtype=torch.float16,
        quantization_config=bnb_config,
    )
else:
    # for full fine-tuning, we can speed up the model using Flash Attention
    # only available on certain devices, see https://github.com/Dao-AILab/flash-attention?tab=readme-ov-file#installation-and-features
    model = LlavaNextForConditionalGeneration.from_pretrained(
        MODEL_ID,
        torch_dtype=torch.float16,
        _attn_implementation="flash_attention_2",
    )


def find_all_linear_names(model):
    cls = torch.nn.Linear
    lora_module_names = set()
    multimodal_keywords = ['multi_modal_projector', 'vision_model']
    for name, module in model.named_modules():
        if any(mm_keyword in name for mm_keyword in multimodal_keywords):
            continue
        if isinstance(module, cls):
            names = name.split('.')
            lora_module_names.add(names[0] if len(names) == 1 else names[-1])

    if 'lm_head' in lora_module_names: # needed for 16-bit
        lora_module_names.remove('lm_head')
    return list(lora_module_names)


lora_config = LoraConfig(
    r=8,
    lora_alpha=8,
    lora_dropout=0.1,
    target_modules=find_all_linear_names(model),
    init_lora_weights="gaussian",
)


base_model = model

model = prepare_model_for_kbit_training(model)
model = get_peft_model(model, lora_config)


from peft import LoraConfig, prepare_model_for_kbit_training, get_peft_model





##############################


class LlavaModelPLModule(L.LightningModule):
    def __init__(self, config, processor, model):
        super().__init__()
        self.config = config
        self.processor = processor
        self.model = model

        self.batch_size = config.get("batch_size")

    def training_step(self, batch, batch_idx):

        input_ids, attention_mask, pixel_values, image_sizes, labels = batch

        outputs = self.model(input_ids=input_ids,
                            attention_mask=attention_mask,
                            pixel_values=pixel_values,
                            image_sizes=image_sizes,
                            labels=labels
                          )
        loss = outputs.loss

        self.log("train_loss", loss)

        return loss

    def validation_step(self, batch, batch_idx, dataset_idx=0):

        input_ids, attention_mask, pixel_values, image_sizes, answers = batch

        # autoregressively generate token IDs
        generated_ids = self.model.generate(input_ids=input_ids, attention_mask=attention_mask,
                                       pixel_values=pixel_values, image_sizes=image_sizes, max_new_tokens=MAX_LENGTH)
        # turn them back into text, chopping of the prompt
        # important: we don't skip special tokens here, because we want to see them in the output
        predictions = self.processor.batch_decode(generated_ids[:, input_ids.size(1):], skip_special_tokens=True)

        scores = []
        for pred, answer in zip(predictions, answers):
            pred = re.sub(r"(?:(?<=>) | (?=</s_))", "", pred)
            scores.append(edit_distance(pred, answer) / max(len(pred), len(answer)))

            if self.config.get("verbose", False) and len(scores) == 1:
                print(f"Prediction: {pred}")
                print(f"    Answer: {answer}")
                print(f" Normed ED: {scores[0]}")

        self.log("val_edit_distance", np.mean(scores))

        return scores

    def configure_optimizers(self):
        # you could also add a learning rate scheduler if you want
        optimizer = torch.optim.AdamW(self.parameters(), lr=self.config.get("lr"))

        return optimizer

    def train_dataloader(self):
        return DataLoader(train_dataset, collate_fn=train_collate_fn, batch_size=self.batch_size, shuffle=True, num_workers=4)

    def val_dataloader(self):
        return DataLoader(val_dataset, collate_fn=eval_collate_fn, batch_size=self.batch_size, shuffle=False, num_workers=4)


from pytorch_lightning import Trainer



config = {"max_epochs": epochs ,
          # "val_check_interval": 0.2, # how many times we want to validate during an epoch
          "check_val_every_n_epoch": 1,
          "gradient_clip_val": 1.0,
          "accumulate_grad_batches": 8,
          "lr": 1e-4,
          "batch_size": 1,
          # "seed":2022,
          "num_nodes": 1,
          "warmup_steps": 50,
          "result_path": "./result",
          "verbose": True,}




#model = LlavaModelPLModule(config, processor, model)



model_path = root_dir + f"/testing_eve_jobmodels/fine_tuned_models/llava-v1.6-mistral-7b-hf_{epochs}e_qa_qa"


#checkpoint = torch.load('model_path/checkpoint.ckpt')

"""
model = LlavaModelPLModule.load_from_checkpoint(f"{model_path}/checkpoint.ckpt",
                                                config,
                                                processor,
                                                model)
"""


#loading the model with the checkpoint!                                                

model = LlavaModelPLModule.load_from_checkpoint(
    f"{model_path}/checkpoint.ckpt",
    hparams_file=None,
    config=config,
    processor=processor,
    model= model
)



#model.load_state_dict(checkpoint['model_state_dict'])


print(model)


model.eval()


model = model.to(device)



from datasets import load_dataset

dataset = load_dataset("naver-clova-ix/cord-v2")


test_example = dataset["test"][3]
test_image = test_example["image"]


#prepare image and prompt for the model
#To do this can be replaced by apply_chat_template when the processor supports this
prompt = f"[INST] <image>\nExtract JSON [\INST]"
inputs = processor(text=prompt, images=[test_image], return_tensors="pt").to("cuda")
for k,v in inputs.items():
    print(k,v.shape)

# Generate token IDs
generated_ids = model.model.generate(**inputs, max_new_tokens=MAX_LENGTH)

# Decode back into text
generated_texts = processor.batch_decode(generated_ids, skip_special_tokens=True)

print(generated_texts)

#processor = AutoProcessor.from_pretrained(model_path)


import re

# let's turn that into JSON
def token2json(tokens, is_inner_value=False, added_vocab=None):
        """
        Convert a (generated) token sequence into an ordered JSON format.
        """
        if added_vocab is None:
            added_vocab = processor.tokenizer.get_added_vocab()

        output = {}

        while tokens:
            start_token = re.search(r"<s_(.*?)>", tokens, re.IGNORECASE)
            if start_token is None:
                break
            key = start_token.group(1)
            key_escaped = re.escape(key)

            end_token = re.search(rf"</s_{key_escaped}>", tokens, re.IGNORECASE)
            start_token = start_token.group()
            if end_token is None:
                tokens = tokens.replace(start_token, "")
            else:
                end_token = end_token.group()
                start_token_escaped = re.escape(start_token)
                end_token_escaped = re.escape(end_token)
                content = re.search(
                    f"{start_token_escaped}(.*?){end_token_escaped}", tokens, re.IGNORECASE | re.DOTALL
                )
                if content is not None:
                    content = content.group(1).strip()
                    if r"<s_" in content and r"</s_" in content:  # non-leaf node
                        value = token2json(content, is_inner_value=True, added_vocab=added_vocab)
                        if value:
                            if len(value) == 1:
                                value = value[0]
                            output[key] = value
                    else:  # leaf nodes
                        output[key] = []
                        for leaf in content.split(r"<sep/>"):
                            leaf = leaf.strip()
                            if leaf in added_vocab and leaf[0] == "<" and leaf[-2:] == "/>":
                                leaf = leaf[1:-2]  # for categorical special tokens
                            output[key].append(leaf)
                        if len(output[key]) == 1:
                            output[key] = output[key][0]

                tokens = tokens[tokens.find(end_token) + len(end_token) :].strip()
                if tokens[:6] == r"<sep/>":  # non-leaf nodes
                    return [output] + token2json(tokens[6:], is_inner_value=True, added_vocab=added_vocab)

        if len(output):
            return [output] if is_inner_value else output
        else:
            return [] if is_inner_value else {"text_sequence": tokens}
        


generated_json = token2json(generated_texts[0])
print(generated_json)

for key, value in generated_json.items():
    print(key, value)


###################################################################
###################################################################
###################################################################
""" 

# Pushing the model into the Huggingface hub

#Ali-Forootani/llava-v1.6-mistral-7b-hf_20epochs_fine_tune

# Specify the directory where the model and processor will be saved
model_save_path = model_path + "./saved_model"

# Save the processor
processor.save_pretrained(model_save_path)

# Save the model
model.model.save_pretrained(model_save_path)

from transformers import AutoProcessor, LlavaNextForConditionalGeneration

# Load the saved processor and model
processor = AutoProcessor.from_pretrained(model_save_path)
model = LlavaNextForConditionalGeneration.from_pretrained(model_save_path)

# Push the processor and model to the Hugging Face Hub
from huggingface_hub import HfApi, login
login(token="your_huggingface_token")
processor.push_to_hub("your_hf_id/llava-v1.6-mistral-7b-hf_100epochs_fine_tune", use_auth_token=True)
model.push_to_hub("your_hf_id/llava-v1.6-mistral-7b-hf_100epochs_fine_tune", use_auth_token=True)


from huggingface_hub import HfApi, login
from peft import LoraConfig, PeftModel, prepare_model_for_kbit_training

"""


#############################
############################# Second way to push to huggingface

from huggingface_hub import HfApi, login
# Login to Hugging Face
login(token="your_huggingface_token")

# Define your Hugging Face repository name
# repo_name = "your_hf_id/llava-v1.6-mistral-7b_fine_tune_20epochs"
repo_name = "your_hf_id/llava-v1.6-mistral-7b-hf_100epochs_fine_tune"

#######



# Save the model and processor locally model_path 
#output_dir = model_path + "/model_to_push"
#model.model.save_pretrained(output_dir)
#processor.save_pretrained(output_dir)

# Push to Hugging Face Hub
model.model.push_to_hub(repo_name, use_auth_token=True)
processor.push_to_hub(repo_name, use_auth_token=True)
```



[More Information Needed]
