Fine-Tune Falcon 180B with DeepSpeed ZeRO, LoRA & Flash Attention on E2E Cloud

November 22, 2023

The Falcon 180B is a monumental language model pioneered by Abu Dhabi's Technology Innovation Institute (TII). As an extension of the preceding ‘Falcon’ series, particularly Falcon 40B, Falcon 180B amplifies its predecessor's capabilities. This auto-regressive language model employs a refined transformer architecture and was educated using a vast dataset of 3.5 trillion tokens. Boasting a staggering 180 billion parameters, Falcon 180B claims the title of the most expansive open-source Large Language Model in existence, catering to both research and business applications. It proudly occupies the top position on the Hugging Face Leaderboard for open-source LLMs.

Now, let's delve into the process of fine-tuning Falcon 180B. We'll harness the power of DeepSpeed, Hugging Face Transformers, LoRA, and Flash Attention on a set-up with multiple GPUs.

First, What Exactly Is DeepSpeed ZeRO?

Originating from Microsoft Research, ZeRO, which stands for Zero Redundancy Optimizer, is a groundbreaking memory optimization solution tailored for expansive distributed deep learning. It introduces a novel optimizer that drastically curtails the resources demanded by model and data parallelism, while simultaneously amplifying the trainable parameter count. ZeRO has been engineered to eradicate memory overlaps in both data and model parallel training, ensuring minimized communication overhead and maximized computational precision. This ensures a scalable model size that aligns with the number of available devices, all while maintaining peak efficiency.

Incorporated within DeepSpeed, an open-source toolkit from Microsoft Research, ZeRO propels large model training by enhancing scalability, speed, affordability, and user experience. This makes a 100-billion-parameter model training achievable. Designed to complement PyTorch, DeepSpeed provides comprehensive support for all stages of ZeRO, namely stages 1, 2, and 3, and also facilitates CPU and Disk offloading for optimizer states, gradients, and parameters.

What Is LoRA?

LoRA, or Low-Rank Adaptation, is a specialized training method applied in various domains, including the generation of AI-driven art and the optimization of language models. In the realm of AI art, LoRA aids in the fine-tuning of Stable Diffusion models. It allows the system to be trained on distinct concepts, whether they be specific characters or artistic styles, by enacting minimal alterations to the related model file. Notably, models developed using LoRA are much more compact than standard checkpoint models, offering a convenient solution for those limited by storage capacity.

When applied to language models, particularly those as expansive as GPT-3 with its billions of parameters, LoRA offers a refined approach to fine-tuning. Instead of altering the vast number of pre-trained weights, LoRA introduces trainable layers within each transformer block, thereby cutting down on the number of adjustable parameters and the GPU memory they consume. This strategy bypasses the need to compute gradients for the majority of model weights, which expedites the fine-tuning process. With LoRA, models can be fine-tuned using a fraction of the parameters typically required, marking a significant improvement over conventional methods.

In essence, LoRA stands out as a pivotal training approach, beneficial for fine-tuning both AI-generated art models and mammoth language models. It introduces efficiencies by modifying model files with slight changes and providing compact models that are storage-friendly. Furthermore, in the landscape of language models, LoRA enhances the fine-tuning process, making it both faster and more resource-efficient.

What Is Flash Attention?

Flash Attention is an optimization algorithm designed to accelerate the attention mechanism within Transformer-based language models. The attention mechanism, a vital component in Transformers, allows the model to focus on different parts of the input sequence when making predictions. However, this mechanism can be computationally expensive, particularly when processing longer text sequences, leading to high memory costs and slower processing times.

The Flash Attention algorithm addresses this issue through a series of techniques. It utilizes methods such as tiling, which involves dividing the input sequence into smaller segments, and recomputation, which involves recalculating certain values to reduce memory usage. These techniques help to streamline the computations involved in the attention mechanism, thereby enhancing the model's efficiency in handling longer text sequences.

Flash Attention-2 is an improved version of the original algorithm that further optimizes the parallelism and work partitioning of computations. By refining the distribution of tasks and enhancing parallel processing capabilities, Flash Attention-2 achieves a notable 2x speedup compared to its predecessor. This enhancement is especially significant as it enables the algorithm to reach a high processing speed of 230 TFLOPS/s (tera floating-point operations per second) on A100 GPUs, indicating a substantial improvement in computational performance and efficiency.

Steps for Fine-Tuning Falcon 180B with DeepSpeed ZeRO, LoRA & Flash Attention on E2E Cloud

1. We have to first make sure that we have accepted the license tiiuae/falcon-180B to be able to use it. You can accept the license by clicking on the Agree and Access Repository button on the model page at https://huggingface.co/tiiuae/falcon-180B.

2. Launch a GPU node on the E2E Cloud Computing platform.

For this article, we will be using the NVIDIA-A-100 node.

3. Set up the environment.


conda create --name hf python=3.10 -c conda-forge

When you execute this command, Conda will set up a new isolated environment named ‘hf’ with Python 3.10 installed within it. This will allow you to work on projects that specifically require this environment without affecting other Python projects or environments on your system. Additionally, the use of the ‘conda-forge’ channel ensures that packages from this community-driven repository are used for the environment.


# install torch with the correct cuda version, check nvcc --version
!pip install torch --extra-index-url https://download.pytorch.org/whl/cu118 --upgrade
# install Hugging Face Libraries and additional dependencies
!pip install "transformers==4.33.1" "datasets==2.14.5" "accelerate==0.22.0" "evaluate==0.4.0" "peft==0.5.0" tensorboard packaging --upgrade
# install deepspeed and ninja for jit compilations of kernels
!pip install "deepspeed==0.10.3" ninja --upgrade
# install additional Flash Attention
!pip install flash-attn --no-build-isolation --upgrade

Let’s log in into our Hugging Face account by running the following command: 


!huggingface-cli login --token YOUR_TOKEN

The purpose of this command is to authenticate the user's identity on the Hugging Face Hub and enable them to perform various actions on the Hub.

4. Load and pre-process the dataset.

We'll work with ‘Dolly’, an open-source dataset containing instruction-following records produced by numerous Databricks employees. The dataset falls into various behavioral categories detailed in the InstructGPT paper, such as brainstorming, classification, closed QA, generation, information extraction, open QA, and summarization.


{
"instruction": "When was the wheel invented?",
"context": "",
"response": "No one knows when the wheel was first made. Archaeological evidence seems to show that the wheel was first used to make pottery in Mesopotamia about 7,000 years ago, during the Neolithic period. Later, it was used to make chariots. Chariot wheels have been found in Sumer as early as 3000 BC. The wheel is one of the most important inventions in human history. It was very useful for making pottery and getting around on land. It is also a key part of machines."
}

We use the load_dataset() method from the Hugging Face Datasets library.


from datasets import load_dataset
from random import randrange
# Load dataset from the hub
dataset = load_dataset("databricks/databricks-dolly-15k", split="train")
print(f"dataset size: {len(dataset)}")
print(dataset[randrange(len(dataset))])
# dataset size: 15011

To fine-tune our model effectively, we are required to transform our organized examples into a set of tasks specified by instructions. We establish a formatting function designed to accept a sample and produce a string containing our formatted instruction.


def format_dolly(sample):
    instruction = f"### Instruction\n{sample['instruction']}"
    context = f"### Context\n{sample['context']}" if len(sample["context"])     > 0 else None
    response = f"### Answer\n{sample['response']}"
# join all the parts together
    prompt = "\n\n".join([i for i in [instruction, context, response] if i is not None])
    return prompt
    

Let's test our formatting function on a random example.


from random import randrange
print(format_dolly(dataset[randrange(len(dataset))]))

Also, apart from formatting our samples, we aim to consolidate multiple samples into one sequence to enhance the efficiency of our training.


from transformers import AutoTokenizer
model_id = "tiiuae/falcon-180B"
tokenizer = AutoTokenizer.from_pretrained(model_id)
tokenizer.pad_token = tokenizer.eos_token

We create several auxiliary functions to bundle our samples into sequences of a specified length, and subsequently tokenize them.


# Print random sample
print(dataset[randint(0, len(dataset))]["text"])
# Empty list to save remainder from batches to use in next batch
remainder = {"input_ids": [], "attention_mask": [], "token_type_ids": []}
 
def chunk(sample, chunk_length=2048):
# define global remainder variable to save remainder from batches to use in next batch
    global remainder

# Concatenate all texts and add remainder from previous batch
    concatenated_examples = {k: list(chain(*sample[k])) for k in sample.keys()}
    concatenated_examples = {k: remainder[k] + concatenated_examples[k] for k in concatenated_examples.keys()}

# get total number of tokens for batch
    batch_total_length = len(concatenated_examples[list(sample.keys())[0]])

# get max number of chunks for batch
    if batch_total_length >= chunk_length:
        batch_chunk_length = (batch_total_length // chunk_length) * chunk_length

# Split by chunks of max_len.
    result = {
k: [t[i : i + chunk_length] for i in range(0, batch_chunk_length, chunk_length)]
    for k, t in concatenated_examples.items()
}

# add remainder to global variable for next batch
    remainder = {k: concatenated_examples[k][batch_chunk_length:] for k in concatenated_examples.keys()}

# prepare labels
    result["labels"] = result["input_ids"].copy()
    return result

# tokenize and chunk dataset
lm_dataset = dataset.map(
lambda sample: tokenizer(sample["text"]), batched=True,     remove_columns=list(dataset.features)
).map(
    partial(chunk, chunk_length=2048),
batched=True,
)

# Print total number of samples
print(f"Total number of samples: {len(lm_dataset)}")

Once we have processed the datasets, our intention is to store them on disk so that we can utilize the processed dataset later for training purposes.


lm_dataset.save_to_disk("dolly-processed")

5. Fine-tune Falcon 180B using DeepSpeed, Hugging Face Transformers, and LoRA with Flash Attention.

The Hugging Face Transformers Trainer seamlessly incorporates DeepSpeed ZeRO, allowing for easy utilization with the provision of a DeepSpeed config file, with the Trainer managing the process. Two DeepSpeed configurations, including CPU offloading, were generated for our experiments.

ds_falcon_180b_z3.json 


{
  "bf16": {
    "enabled": "auto"
  },
  "optimizer": {
    "type": "AdamW",
    "params": {
      "lr": "auto",
      "betas": "auto",
      "eps": "auto",
      "weight_decay": "auto"
    }
  },
  "scheduler": {
    "type": "WarmupLR",
    "params": {
      "warmup_min_lr": "auto",
      "warmup_max_lr": "auto",
      "warmup_num_steps": "auto"
    }
  },
  "zero_optimization": {
    "stage": 3,
    "overlap_comm": true,
    "contiguous_gradients": true,
    "sub_group_size": 1e9,
    "reduce_bucket_size": "auto",
    "stage3_prefetch_bucket_size": "auto",
    "stage3_param_persistence_threshold": "auto",
    "stage3_max_live_parameters": 1e9,
    "stage3_max_reuse_distance": 1e9,
    "stage3_gather_16bit_weights_on_model_save": true
  },
  "gradient_accumulation_steps": "auto",
  "gradient_clipping": "auto",
  "steps_per_print": 2000,
  "train_batch_size": "auto",
  "train_micro_batch_size_per_gpu": "auto",
  "wall_clock_breakdown": false
}



ds_falcon_180b_z3_offload.json

{
  "bf16": {
    "enabled": "auto"
  },
  "optimizer": {
    "type": "AdamW",
    "params": {
      "lr": "auto",
      "betas": "auto",
      "eps": "auto",
      "weight_decay": "auto"
    }
  },
  "scheduler": {
    "type": "WarmupLR",
    "params": {
      "warmup_min_lr": "auto",
      "warmup_max_lr": "auto",
      "warmup_num_steps": "auto"
    }
  },
  "zero_optimization": {
    "stage": 3,
    "offload_optimizer": {
      "device": "cpu",
      "pin_memory": true
    },
    "offload_param": {
      "device": "cpu",
      "pin_memory": true
    },
    "overlap_comm": true,
    "contiguous_gradients": true,
    "sub_group_size": 1e9,
    "reduce_bucket_size": "auto",
    "stage3_prefetch_bucket_size": "auto",
    "stage3_param_persistence_threshold": "auto",
    "stage3_max_live_parameters": 1e9,
    "stage3_max_reuse_distance": 1e9,
    "stage3_gather_16bit_weights_on_model_save": true
  },
  "gradient_accumulation_steps": "auto",
  "gradient_clipping": "auto",
  "steps_per_print": 2000,
  "train_batch_size": "auto",
  "train_micro_batch_size_per_gpu": "auto",
  "wall_clock_breakdown": false
}

ds_falcon_180b_z3_offload.json


{
  "bf16": {
    "enabled": "auto"
  },
  "optimizer": {
    "type": "AdamW",
    "params": {
      "lr": "auto",
      "betas": "auto",
      "eps": "auto",
      "weight_decay": "auto"
    }
  },
  "scheduler": {
    "type": "WarmupLR",
    "params": {
      "warmup_min_lr": "auto",
      "warmup_max_lr": "auto",
      "warmup_num_steps": "auto"
    }
  },
  "zero_optimization": {
    "stage": 3,
    "offload_optimizer": {
      "device": "cpu",
      "pin_memory": true
    },
    "offload_param": {
      "device": "cpu",
      "pin_memory": true
    },
    "overlap_comm": true,
    "contiguous_gradients": true,
    "sub_group_size": 1e9,
    "reduce_bucket_size": "auto",
    "stage3_prefetch_bucket_size": "auto",
    "stage3_param_persistence_threshold": "auto",
    "stage3_max_live_parameters": 1e9,
    "stage3_max_reuse_distance": 1e9,
    "stage3_gather_16bit_weights_on_model_save": true
  },
  "gradient_accumulation_steps": "auto",
  "gradient_clipping": "auto",
  "steps_per_print": 2000,
  "train_batch_size": "auto",
  "train_micro_batch_size_per_gpu": "auto",
  "wall_clock_breakdown": false
}

Alongside the DeepSpeed configuration, we require a training script that incorporates LoRA and integrates flash-attention into our model via the falcon_patch.py utilities. Our run_ds_lora.py script has been designed for this purpose, incorporating the implementation of LoRA with the assistance of peft_utils.py.

run_ds_lora.py


from dataclasses import dataclass, field
from typing import cast

import os
import subprocess
from typing import Optional
import torch

from transformers import HfArgumentParser, TrainingArguments, Trainer
from object_detection.utils.peft_utils import SaveDeepSpeedPeftModelCallback, create_and_prepare_model
from datasets import load_from_disk


# Define and parse arguments.
@dataclass
class ScriptArguments:
    """
    Additional arguments for training, which are not part of TrainingArguments.
    """
    model_id: str = field(
      metadata={
            "help": "The model that you want to train from the Hugging Face hub. E.g. gpt2, gpt2-xl, bert, etc."
        },
    )
    dataset_path: Optional[str] = field(
        default="timdettmers/openassistant-guanaco",
        metadata={"help": "The preference dataset to use."},
    )
    lora_alpha: Optional[int] = field(default=16)
    lora_dropout: Optional[float] = field(default=0.1)
    lora_r: Optional[int] = field(default=64)
    use_flash_attn: Optional[bool] = field(
        default=False,
        metadata={"help": "Enables Flash attention for training."},
    )
    merge_adapters: bool = field(
        metadata={"help": "Whether to merge weights for LoRA."},
        default=False,
    )


def training_function(script_args:ScriptArguments, training_args:TrainingArguments):

    # Load processed dataset from disk
    dataset = load_from_disk(script_args.dataset_path)
   
    # Load and create peft model
    model, peft_config, tokenizer = create_and_prepare_model(script_args.model_id,training_args, script_args)
    model.config.use_cache = False


    # Create trainer and add callbacks
    trainer = Trainer(model=model, args=training_args, train_dataset=dataset)
    trainer.accelerator.print(f"{trainer.model}")
    trainer.model.print_trainable_parameters()
    trainer.add_callback(SaveDeepSpeedPeftModelCallback(trainer, save_steps=training_args.save_steps))
   
    # Start training
    trainer.train()

    # Save model on main process
    trainer.accelerator.wait_for_everyone()
    state_dict = trainer.accelerator.get_state_dict(trainer.deepspeed)
    unwrapped_model = trainer.accelerator.unwrap_model(trainer.deepspeed)
    if trainer.accelerator.is_main_process:
        unwrapped_model.save_pretrained(training_args.output_dir, state_dict=state_dict)
    trainer.accelerator.wait_for_everyone()

    # TODO: add merge adapters
    # Save everything else on main process
    if trainer.args.process_index == 0:
        if script_args.merge_adapters:
            # merge adapter weights with base model and save
            # save int 4 model
            trainer.model.save_pretrained(training_args.output_dir, safe_serialization=False)
            # clear memory
            del model
            del trainer
            torch.cuda.empty_cache()

            from peft import AutoPeftModelForCausalLM

            # load PEFT model in fp16
            model = AutoPeftModelForCausalLM.from_pretrained(
                training_args.output_dir,
                low_cpu_mem_usage=True,
                torch_dtype=torch.float16,
            )  
            # Merge LoRA and base model and save
            model = model.merge_and_unload()        
            model.save_pretrained(
                training_args.output_dir, safe_serialization=True, max_shard_size="8GB"
            )
        else:
            trainer.model.save_pretrained(
                training_args.output_dir, safe_serialization=True
            )

        # save tokenizer
        tokenizer.save_pretrained(training_args.output_dir)


def main():
    parser = HfArgumentParser([ScriptArguments,TrainingArguments])
    script_args, training_args = parser.parse_args_into_dataclasses()
    script_args = cast(ScriptArguments, script_args)
    training_args = cast(TrainingArguments, training_args)
   
    training_function(script_args, training_args)


if __name__ == "__main__":
    main()
    

peft_utils.py


import torch
from transformers import TrainerCallback, TrainingArguments, TrainerState, TrainerControl
from peft import LoraConfig, get_peft_model
from peft.tuners.lora import LoraLayer
from transformers import (
    AutoModelForCausalLM,
    AutoTokenizer,
    AutoTokenizer,
    TrainingArguments,
)
from utils.falcon_patch import replace_attn_with_flash_attn as replace_falcon_attn_with_flash_attn
from utils.llama_patch import replace_attn_with_flash_attn as replace_llama_attn_with_flash_attn


class SaveDeepSpeedPeftModelCallback(TrainerCallback):
    def __init__(self, trainer, save_steps=500):
        self.trainer = trainer
        self.save_steps = save_steps

    def on_step_end(
        self,
        args: TrainingArguments,
        state: TrainerState,
        control: TrainerControl,
        **kwargs,
    ):
        if (state.global_step + 1) % self.save_steps == 0:
            self.trainer.accelerator.wait_for_everyone()
            state_dict = self.trainer.accelerator.get_state_dict(self.trainer.deepspeed)
            unwrapped_model = self.trainer.accelerator.unwrap_model(self.trainer.deepspeed)
            if self.trainer.accelerator.is_main_process:
                unwrapped_model.save_pretrained(args.output_dir, state_dict=state_dict)
            self.trainer.accelerator.wait_for_everyone()
        return control


def create_and_prepare_model(model_id: str, training_args: TrainingArguments, script_args):
    model = AutoModelForCausalLM.from_pretrained(
        model_id,
        use_cache=not training_args.gradient_checkpointing,
        use_flash_attention_2=script_args.use_flash_attn,
    )
    print("model loaded")

    # find all linear modules in model for lora
    target_modules = find_all_linear_names(model)

    # create lora config
    peft_config = LoraConfig(
        lora_alpha=script_args.lora_alpha,
        lora_dropout=script_args.lora_dropout,
        r=script_args.lora_r,
        bias="none",
        task_type="CAUSAL_LM",
        target_modules=target_modules,
    )
    # enable gradient checkpointing
    if training_args.gradient_checkpointing:
        model.gradient_checkpointing_enable()

    # pre-process the model by upcasting the layer norms in float 32 for
    # Adapted from https://github.com/tmm1/axolotl/blob/2eda9e02a9d15a7a3f92b41f257d9844d72fc220/src/axolotl/utils/models.py#L338
    print("pre-processing model for peft")
    for name, module in model.named_modules():
        if isinstance(module, LoraLayer):
            module = module.to(torch.bfloat16)
        if "norm" in name:
            module = module.to(torch.bfloat16)
        if any(x in name for x in ["lm_head", "embed_tokens", "wte", "wpe"]):
            if hasattr(module, "weight"):
                module = module.to(torch.bfloat16)

    # initialize peft model
    print("initializing peft model")
    model = get_peft_model(model, peft_config)

    # logger.info parameters
    model.print_trainable_parameters()

    # tokenizer
    tokenizer = AutoTokenizer.from_pretrained(model_id)
    tokenizer.pad_token = tokenizer.eos_token

    return model, peft_config, tokenizer


def find_all_linear_names(model):
    cls = torch.nn.Linear
    lora_module_names = set()
    for name, module in model.named_modules():
        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)

falcon_patch.py


from typing import List, Optional, Tuple

import torch
import transformers
from peft.tuners.lora import LoraLayer

try:
    from flash_attn import flash_attn_func
except Exception:
    raise ModuleNotFoundError(
        "Please install FlashAttention first, e.g., with pip install flash-attn --no-build-isolation, Learn more at https://github.com/Dao-AILab/flash-attention#installation-and-features"
    )

try:
    from einops import rearrange
except Exception:
    raise ModuleNotFoundError("Please install einops first, e.g., with pip install einops")


# ADAPTED https://github.com/pacman100/DHS-LLM-Workshop/blob/main/chat_assistant/training/falcon_flash_attn_monkey_patch.py
def forward(
    self,
    hidden_states: torch.Tensor,
    alibi: Optional[torch.Tensor],
    attention_mask: torch.Tensor,
    layer_past: Optional[Tuple[torch.Tensor, torch.Tensor]] = None,
    head_mask: Optional[torch.Tensor] = None,
    use_cache: bool = False,
    output_attentions: bool = False,
):
    fused_qkv = self.query_key_value(hidden_states)  # [batch_size, seq_length, 3 x hidden_size]
    num_kv_heads = self.num_heads if self.new_decoder_architecture else self.num_kv_heads
    # 3 x [batch_size, seq_length, num_heads, head_dim]
    (query_layer, key_layer, value_layer) = self._split_heads(fused_qkv)

    batch_size, query_length, _, _ = query_layer.shape

    query_layer = query_layer.transpose(1, 2).reshape(batch_size * self.num_heads, query_length, self.head_dim)
    key_layer = key_layer.transpose(1, 2).reshape(
        batch_size * num_kv_heads,
        query_length,
        self.head_dim,
    )
    value_layer = value_layer.transpose(1, 2).reshape(batch_size * num_kv_heads, query_length, self.head_dim)

    past_kv_length = 0 if layer_past is None else layer_past[0].shape[1]
    query_layer, key_layer = self.maybe_rotary(query_layer, key_layer, past_kv_length)

    if layer_past is not None:
        past_key, past_value = layer_past
        # concatenate along seq_length dimension:
        #  - key: [batch_size * self.num_heads, kv_length, head_dim]
        #  - value: [batch_size * self.num_heads, kv_length, head_dim]
        key_layer = torch.cat((past_key, key_layer), dim=1)
        value_layer = torch.cat((past_value, value_layer), dim=1)

    _, kv_length, _ = key_layer.shape
    if use_cache:
        present = (key_layer, value_layer)
    else:
        present = None
    attention_mask_float = (attention_mask * 1.0).masked_fill(attention_mask, float("-1e9")).to(query_layer.dtype)
    query_layer_ = (
        query_layer.reshape(batch_size, self.num_heads, -1, self.head_dim).transpose(1, 2).to(torch.bfloat16)
    )
    key_layer_ = key_layer.reshape(batch_size, num_kv_heads, -1, self.head_dim).transpose(1, 2).to(torch.bfloat16)
    value_layer_ = value_layer.reshape(batch_size, num_kv_heads, -1, self.head_dim).transpose(1, 2).to(torch.bfloat16)

    if alibi is not None:
        raise ValueError("`alibi` is not supported when `use_flash_attn` is True")

    # below output will have shape (batch_size, seqlen, nheads, headdim)
    attn_output = flash_attn_func(query_layer_, key_layer_, value_layer_, causal=True)
    attn_output = attn_output.reshape(batch_size, query_length, self.num_heads * self.head_dim)
    output_tensor = self.dense(attn_output)
    return output_tensor, present


def replace_attn_with_flash_attn():
    cuda_major, cuda_minor = torch.cuda.get_device_capability()
    if cuda_major < 8:
        print(
            "Flash attention is only supported on Ampere or Hopper GPU during training due to head dim > 64 backward."
            "ref: https://github.com/HazyResearch/flash-attention/issues/190#issuecomment-1523359593"
        )
    transformers.models.falcon.modeling_falcon.FalconAttention.forward = forward
   

def unplace_flash_attn_with_attn():
    import importlib
    import transformers

    print("Reloading falcon model, unpatching flash attention")
    importlib.reload(transformers.models.falcon.modeling_falcon)


# Adapted from https://github.com/tmm1/axolotl/blob/2eda9e02a9d15a7a3f92b41f257d9844d72fc220/src/axolotl/utils/models.py#L338
def upcast_layer_for_flash_attention(model, torch_dtype):
    # LlamaRMSNorm layers are in fp32 after kbit_training, so we need to
    # convert them back to fp16/bf16 for flash-attn compatibility.
    for name, module in model.named_modules():
        if isinstance(module, LoraLayer):
            module.to(torch_dtype)
        if "norm" in name:
            module.to(torch_dtype)
        if "lm_head" in name or "embed_tokens" in name:
            if hasattr(module, "weight"):
                module.to(torch_dtype)

    return model

Upon confirming the appropriate configuration and training script, we can initiate the training process using torchrun.


!torchrun --nproc_per_node 8 run_ds_lora.py \
--model_id tiiuae/falcon-180B \
--dataset_path dolly-processed \
--output_dir falcon-180b-lora-fa \
--num_train_epochs 3 \
--per_device_train_batch_size 1 \
--learning_rate 4e-3 \
--gradient_checkpointing True \
--gradient_accumulation_steps 8 \
--bf16 True \
--tf32 True \
--use_flash_attn True \
--lr_scheduler_type "constant_with_warmup" \
--logging_steps 25 \
--save_steps 100 \
--save_total_limit 3 \
--deepspeed configs/ds_falcon_180b_z3.json

Please note that due to our usage of LoRA, we are solely saving the ‘trained’ adapter weights to conserve storage space. If you intend to consolidate the adapters back into the base model and preserve the merged model, you can either include ‘--merge_adapters True’ or employ the merge_adapter_weights.py script.

merge_adapter_weights.py


from dataclasses import dataclass, field
from typing import Optional
import torch
from peft import AutoPeftModelForCausalLM
from transformers import AutoTokenizer, HfArgumentParser

# execute script
# python scripts/merge_peft_into_model.py --peft_model_id falcon-180b-lora-fa --output_dir merged-weights --save_tokenizer True

@dataclass
class ScriptArguments:
    peft_model_id: str = field(metadata={"help": "model id or path to model"})
    output_dir: Optional[str] = field(default="merged-weights", metadata={"help": "where the merged model should be saved"})
    save_tokenizer: Optional[bool] = field(default=True, metadata={"help": "whether to save the tokenizer"})
    push_to_hub: Optional[bool] = field(default=False, metadata={"help": "whether to push the model to the hub"})
    repository_id: Optional[str] = field(default=None, metadata={"help": "the model name"})

parser = HfArgumentParser(ScriptArguments)
args = parser.parse_args_into_dataclasses()[0]

model = AutoPeftModelForCausalLM.from_pretrained(
    args.peft_model_id,
    low_cpu_mem_usage=True,
    torch_dtype=torch.float16,
)  
# Merge LoRA and base model and save
model = model.merge_and_unload()        
model.save_pretrained(args.output_dir, safe_serialization=True, max_shard_size="4GB")

if args.save_tokenizer:
    tokenizer = AutoTokenizer.from_pretrained(args.peft_model_id)
    tokenizer.save_pretrained(args.output_dir)
    
if args.push_to_hub:
  if args.repository_id is None:
    raise ValueError("You must specify a repository id to push to the hub")
  from huggingface_hub import HfApi
  api = HfApi()
  api.upload_folder(
    folder_path=args.output_dir,
    repo_id=args.repository_id,
    repo_type="model",
  )
  

6. Inference on Falcon 180B after fine-tuning with LoRA.

Here is an example code snippet that shows how to perform inference on Falcon 180B after fine-tuning with LoRA:


import torch from transformers
import AutoModelForCausalLM, AutoTokenizer 
from utils.peft_utils import LoadLoRAAdapterCallback

 # Load the pre-trained model and the fine-tuned adapter model_name = "tiiuae/falcon-180B" 
model = AutoModelForCausalLM.from_pretrained(model_name)
 
tokenizer = AutoTokenizer.from_pretrained(model_name) 
adapter_path = "path/to/fine-tuned/adapter" 
adapter_callback = LoadLoRAAdapterCallback(adapter_path)
 # Use the fine-tuned adapter to modify the pre-trained model model = adapter_callback.on_init_end(model) 

# Generate text using the modified model
prompt = "The quick brown fox jumps over the lazy dog" 
input_ids = tokenizer.encode(prompt, return_tensors="pt") 
output = model.generate(input_ids) 
# Decode the generated text 
generated_text = tokenizer.decode(output[0], skip_special_tokens=True) 
print(generated_text)

Conclusion

In the blog post, we provided a detailed account of our process for refining the Falcon 180B model, utilizing a combination of DeepSpeed, Hugging Face Transformers, and LoRA with Flash Attention on a multi-GPU set-up. The primary components of our approach included:

1. Exploiting DeepSpeed ZeRO, specifically stage 3 (ZeRO-Infinity), to optimize memory usage and enable the training of models with trillions of parameters within constrained GPU memory.

2. Employing Hugging Face Transformers and Datasets for seamless loading and preparation of the text dataset, facilitated by the user-friendly Trainer API.

3. Implementing LoRA, a methodology that efficiently fine-tunes large LLMs by updating a small subset of parameters during each iteration, thereby significantly reducing memory consumption and computational expenses.

4. Incorporating Flash Attention, a highly optimized attention implementation that further reduces the memory footprint.

5. Conducting inference on the model after training the adapter weights.

By combining these methodologies, we successfully conducted fine-tuning on LLMs with over 100B+ parameters, effectively managing resource constraints. This example serves as a comprehensive template for efficiently fine-tuning the largest publicly accessible models.

Latest Blogs
This is a decorative image for: A Complete Guide To Customer Acquisition For Startups
October 18, 2022

A Complete Guide To Customer Acquisition For Startups

Any business is enlivened by its customers. Therefore, a strategy to constantly bring in new clients is an ongoing requirement. In this regard, having a proper customer acquisition strategy can be of great importance.

So, if you are just starting your business, or planning to expand it, read on to learn more about this concept.

The problem with customer acquisition

As an organization, when working in a diverse and competitive market like India, you need to have a well-defined customer acquisition strategy to attain success. However, this is where most startups struggle. Now, you may have a great product or service, but if you are not in the right place targeting the right demographic, you are not likely to get the results you want.

To resolve this, typically, companies invest, but if that is not channelized properly, it will be futile.

So, the best way out of this dilemma is to have a clear customer acquisition strategy in place.

How can you create the ideal customer acquisition strategy for your business?

  • Define what your goals are

You need to define your goals so that you can meet the revenue expectations you have for the current fiscal year. You need to find a value for the metrics –

  • MRR – Monthly recurring revenue, which tells you all the income that can be generated from all your income channels.
  • CLV – Customer lifetime value tells you how much a customer is willing to spend on your business during your mutual relationship duration.  
  • CAC – Customer acquisition costs, which tells how much your organization needs to spend to acquire customers constantly.
  • Churn rate – It tells you the rate at which customers stop doing business.

All these metrics tell you how well you will be able to grow your business and revenue.

  • Identify your ideal customers

You need to understand who your current customers are and who your target customers are. Once you are aware of your customer base, you can focus your energies in that direction and get the maximum sale of your products or services. You can also understand what your customers require through various analytics and markers and address them to leverage your products/services towards them.

  • Choose your channels for customer acquisition

How will you acquire customers who will eventually tell at what scale and at what rate you need to expand your business? You could market and sell your products on social media channels like Instagram, Facebook and YouTube, or invest in paid marketing like Google Ads. You need to develop a unique strategy for each of these channels. 

  • Communicate with your customers

If you know exactly what your customers have in mind, then you will be able to develop your customer strategy with a clear perspective in mind. You can do it through surveys or customer opinion forms, email contact forms, blog posts and social media posts. After that, you just need to measure the analytics, clearly understand the insights, and improve your strategy accordingly.

Combining these strategies with your long-term business plan will bring results. However, there will be challenges on the way, where you need to adapt as per the requirements to make the most of it. At the same time, introducing new technologies like AI and ML can also solve such issues easily. To learn more about the use of AI and ML and how they are transforming businesses, keep referring to the blog section of E2E Networks.

Reference Links

https://www.helpscout.com/customer-acquisition/

https://www.cloudways.com/blog/customer-acquisition-strategy-for-startups/

https://blog.hubspot.com/service/customer-acquisition

This is a decorative image for: Constructing 3D objects through Deep Learning
October 18, 2022

Image-based 3D Object Reconstruction State-of-the-Art and trends in the Deep Learning Era

3D reconstruction is one of the most complex issues of deep learning systems. There have been multiple types of research in this field, and almost everything has been tried on it — computer vision, computer graphics and machine learning, but to no avail. However, that has resulted in CNN or convolutional neural networks foraying into this field, which has yielded some success.

The Main Objective of the 3D Object Reconstruction

Developing this deep learning technology aims to infer the shape of 3D objects from 2D images. So, to conduct the experiment, you need the following:

  • Highly calibrated cameras that take a photograph of the image from various angles.
  • Large training datasets can predict the geometry of the object whose 3D image reconstruction needs to be done. These datasets can be collected from a database of images, or they can be collected and sampled from a video.

By using the apparatus and datasets, you will be able to proceed with the 3D reconstruction from 2D datasets.

State-of-the-art Technology Used by the Datasets for the Reconstruction of 3D Objects

The technology used for this purpose needs to stick to the following parameters:

  • Input

Training with the help of one or multiple RGB images, where the segmentation of the 3D ground truth needs to be done. It could be one image, multiple images or even a video stream.

The testing will also be done on the same parameters, which will also help to create a uniform, cluttered background, or both.

  • Output

The volumetric output will be done in both high and low resolution, and the surface output will be generated through parameterisation, template deformation and point cloud. Moreover, the direct and intermediate outputs will be calculated this way.

  • Network architecture used

The architecture used in training is 3D-VAE-GAN, which has an encoder and a decoder, with TL-Net and conditional GAN. At the same time, the testing architecture is 3D-VAE, which has an encoder and a decoder.

  • Training used

The degree of supervision used in 2D vs 3D supervision, weak supervision along with loss functions have to be included in this system. The training procedure is adversarial training with joint 2D and 3D embeddings. Also, the network architecture is extremely important for the speed and processing quality of the output images.

  • Practical applications and use cases

Volumetric representations and surface representations can do the reconstruction. Powerful computer systems need to be used for reconstruction.

Given below are some of the places where 3D Object Reconstruction Deep Learning Systems are used:

  • 3D reconstruction technology can be used in the Police Department for drawing the faces of criminals whose images have been procured from a crime site where their faces are not completely revealed.
  • It can be used for re-modelling ruins at ancient architectural sites. The rubble or the debris stubs of structures can be used to recreate the entire building structure and get an idea of how it looked in the past.
  • They can be used in plastic surgery where the organs, face, limbs or any other portion of the body has been damaged and needs to be rebuilt.
  • It can be used in airport security, where concealed shapes can be used for guessing whether a person is armed or is carrying explosives or not.
  • It can also help in completing DNA sequences.

So, if you are planning to implement this technology, then you can rent the required infrastructure from E2E Networks and avoid investing in it. And if you plan to learn more about such topics, then keep a tab on the blog section of the website

Reference Links

https://tongtianta.site/paper/68922

https://github.com/natowi/3D-Reconstruction-with-Deep-Learning-Methods

This is a decorative image for: Comprehensive Guide to Deep Q-Learning for Data Science Enthusiasts
October 18, 2022

A Comprehensive Guide To Deep Q-Learning For Data Science Enthusiasts

For all data science enthusiasts who would love to dig deep, we have composed a write-up about Q-Learning specifically for you all. Deep Q-Learning and Reinforcement learning (RL) are extremely popular these days. These two data science methodologies use Python libraries like TensorFlow 2 and openAI’s Gym environment.

So, read on to know more.

What is Deep Q-Learning?

Deep Q-Learning utilizes the principles of Q-learning, but instead of using the Q-table, it uses the neural network. The algorithm of deep Q-Learning uses the states as input and the optimal Q-value of every action possible as the output. The agent gathers and stores all the previous experiences in the memory of the trained tuple in the following order:

State> Next state> Action> Reward

The neural network training stability increases using a random batch of previous data by using the experience replay. Experience replay also means the previous experiences stocking, and the target network uses it for training and calculation of the Q-network and the predicted Q-Value. This neural network uses openAI Gym, which is provided by taxi-v3 environments.

Now, any understanding of Deep Q-Learning   is incomplete without talking about Reinforcement Learning.

What is Reinforcement Learning?

Reinforcement is a subsection of ML. This part of ML is related to the action in which an environmental agent participates in a reward-based system and uses Reinforcement Learning to maximize the rewards. Reinforcement Learning is a different technique from unsupervised learning or supervised learning because it does not require a supervised input/output pair. The number of corrections is also less, so it is a highly efficient technique.

Now, the understanding of reinforcement learning is incomplete without knowing about Markov Decision Process (MDP). MDP is involved with each state that has been presented in the results of the environment, derived from the state previously there. The information which composes both states is gathered and transferred to the decision process. The task of the chosen agent is to maximize the awards. The MDP optimizes the actions and helps construct the optimal policy.

For developing the MDP, you need to follow the Q-Learning Algorithm, which is an extremely important part of data science and machine learning.

What is Q-Learning Algorithm?

The process of Q-Learning is important for understanding the data from scratch. It involves defining the parameters, choosing the actions from the current state and also choosing the actions from the previous state and then developing a Q-table for maximizing the results or output rewards.

The 4 steps that are involved in Q-Learning:

  1. Initializing parameters – The RL (reinforcement learning) model learns the set of actions that the agent requires in the state, environment and time.
  2. Identifying current state – The model stores the prior records for optimal action definition for maximizing the results. For acting in the present state, the state needs to be identified and perform an action combination for it.
  3. Choosing the optimal action set and gaining the relevant experience – A Q-table is generated from the data with a set of specific states and actions, and the weight of this data is calculated for updating the Q-Table to the following step.
  4. Updating Q-table rewards and next state determination – After the relevant experience is gained and agents start getting environmental records. The reward amplitude helps to present the subsequent step.  

In case the Q-table size is huge, then the generation of the model is a time-consuming process. This situation requires Deep Q-learning.

Hopefully, this write-up has provided an outline of Deep Q-Learning and its related concepts. If you wish to learn more about such topics, then keep a tab on the blog section of the E2E Networks website.

Reference Links

https://analyticsindiamag.com/comprehensive-guide-to-deep-q-learning-for-data-science-enthusiasts/

https://medium.com/@jereminuerofficial/a-comprehensive-guide-to-deep-q-learning-8aeed632f52f

This is a decorative image for: GAUDI: A Neural Architect for Immersive 3D Scene Generation
October 13, 2022

GAUDI: A Neural Architect for Immersive 3D Scene Generation

The evolution of artificial intelligence in the past decade has been staggering, and now the focus is shifting towards AI and ML systems to understand and generate 3D spaces. As a result, there has been extensive research on manipulating 3D generative models. In this regard, Apple’s AI and ML scientists have developed GAUDI, a method specifically for this job.

An introduction to GAUDI

The GAUDI 3D immersive technique founders named it after the famous architect Antoni Gaudi. This AI model takes the help of a camera pose decoder, which enables it to guess the possible camera angles of a scene. Hence, the decoder then makes it possible to predict the 3D canvas from almost every angle.

What does GAUDI do?

GAUDI can perform multiple functions –

  • The extensions of these generative models have a tremendous effect on ML and computer vision. Pragmatically, such models are highly useful. They are applied in model-based reinforcement learning and planning world models, SLAM is s, or 3D content creation.
  • Generative modelling for 3D objects has been used for generating scenes using graf, pigan, and gsn, which incorporate a GAN (Generative Adversarial Network). The generator codes radiance fields exclusively. Using the 3D space in the scene along with the camera pose generates the 3D image from that point. This point has a density scalar and RGB value for that specific point in 3D space. This can be done from a 2D camera view. It does this by imposing 3D datasets on those 2D shots. It isolates various objects and scenes and combines them to render a new scene altogether.
  • GAUDI also removes GANs pathologies like mode collapse and improved GAN.
  • GAUDI also uses this to train data on a canonical coordinate system. You can compare it by looking at the trajectory of the scenes.

How is GAUDI applied to the content?

The steps of application for GAUDI have been given below:

  • Each trajectory is created, which consists of a sequence of posed images (These images are from a 3D scene) encoded into a latent representation. This representation which has a radiance field or what we refer to as the 3D scene and the camera path is created in a disentangled way. The results are interpreted as free parameters. The problem is optimized by and formulation of a reconstruction objective.
  • This simple training process is then scaled to trajectories, thousands of them creating a large number of views. The model samples the radiance fields totally from the previous distribution that the model has learned.
  • The scenes are thus synthesized by interpolation within the hidden space.
  • The scaling of 3D scenes generates many scenes that contain thousands of images. During training, there is no issue related to canonical orientation or mode collapse.
  • A novel de-noising optimization technique is used to find hidden representations that collaborate in modelling the camera poses and the radiance field to create multiple datasets with state-of-the-art performance in generating 3D scenes by building a setup that uses images and text.

To conclude, GAUDI has more capabilities and can also be used for sampling various images and video datasets. Furthermore, this will make a foray into AR (augmented reality) and VR (virtual reality). With GAUDI in hand, the sky is only the limit in the field of media creation. So, if you enjoy reading about the latest development in the field of AI and ML, then keep a tab on the blog section of the E2E Networks website.

Reference Links

https://www.researchgate.net/publication/362323995_GAUDI_A_Neural_Architect_for_Immersive_3D_Scene_Generation

https://www.technology.org/2022/07/31/gaudi-a-neural-architect-for-immersive-3d-scene-generation/ 

https://www.patentlyapple.com/2022/08/apple-has-unveiled-gaudi-a-neural-architect-for-immersive-3d-scene-generation.html

Build on the most powerful infrastructure cloud

A vector illustration of a tech city using latest cloud technologies & infrastructure