OOM error while PPO training Llama-2-7B model
Hi
I am getting OOM while doing PPO fine-tuning. I am fine-tuning the Llama-2-7B on A100 (40GB VRAM) and the reward model (also Llama-2-7B) is kept on a separate A100 (10GB VRAM) for inference. I have tried keeping batch_size, mini_batch_size, and gradient_accumulation all at 1, then also it's throwing OOM with a sudden spike in memory.
Implementing the suggestion of gradient checkpointing throws an AttributeError: AutoModelForCausalLMWithValueHead object has no attribute 'is_peft_model'. Can you tell me how you pass the Lora config and enable checkpointing?
Following code give me error:
lora_config = LoraConfig(
r=64,
lora_alpha=16,
lora_dropout=0.1,
bias="none",
task_type="CAUSAL_LM",
)
model_args = {
"torch_dtype": dtype,
"quantization_config": BitsAndBytesConfig(
load_in_4bit=True,
bnb_4bit_quant_type="nf4",
bnb_4bit_compute_dtype=dtype,
bnb_4bit_use_double_quant=True,
),
"cache_dir": CACHE_DIR,
"device_map": device_map,
}
base_model = transformers.AutoModelForCausalLM.from_pretrained(
conf.model_name, trust_remote_code=True, **model_args
)
base_model.gradient_checkpointing_enable()
base_model = AutoModelForCausalLMWithValueHead(base_model, trust_remote_code=True,peft_config= lora_config)
PPO training loop. Since the data loader set batch_size to batch_size, I am generating one response at a time to avoid OOM.
for epoch, batch in tqdm(enumerate(ppo_trainer.dataloader)):
query_tensor = batch["input_ids"]
# Initialize empty lists to store responses and rewards
response_tensors = []
responses = []
rewards = []
# Iterate through each query in the query_tensor
for idx in range(len(query_tensor)):
single_response_tensor = ppo_trainer.generate(
[query_tensor[idx]],
return_prompt=False,
# length_sampler=512
**generation_kwargs,
)
response = tokenizer.decode(single_response_tensor[0], skip_special_tokens=True)
responses.append(response)
# Prepare input for reward model
text = batch["query"][idx] + response
inputs = tokenizer(text, max_length=2048, padding=True, truncation=True, return_tensors="pt").to(base_reward_model.device)
reward = compute_reward_score(inputs,base_reward_model,conf)
reward = reward[0][0]
# Append the generated response tensor and computed reward
response_tensors.append(single_response_tensor[0])
rewards.append(reward)
# Convert lists to tensors
# response_tensors = torch.cat(response_tensors, dim=0)
batch["response"] = responses
#Run PPO step
stats = ppo_trainer.step(query_tensor, response_tensors, rewards)
rewards = [r.float() if r.dtype == torch.bfloat16 else r for r in rewards]
if epoch%conf.log_step==0:
ppo_trainer.log_stats(stats, batch, rewards)
if epoch > 0 and epoch%conf.save_steps==0:
ppo_trainer.save_pretrained(save_dir + f"/checkpoint_{epoch}")
Can you please tell me what I am doing wrong?
Passing the based model toAutoModelForCausalLMWithValueHead.from_pretrained instead of AutoModelForCausalLMWithValueHead resolve this problem. However, I checked the source code and found the gradient_checkpointing is done by default using prepare_model_for_kbit_training, so I guess no need for manually enable_gradient_checkpointing
So OOM is still there (It occurs only for a specific batch). With the below-mentioned config, it takes more than 40 mins for (some) steps, I can understand manually iterating over the query to generate a response can take extra time but 40 mins for a step is too much. With this speed training the model for 24k queries, it can take one month (If OOM doesn't occur). I am not sure what I am doing wrong.
ppo_config:
steps: 20000 # Number of steps.
model_name: *rl_fine_tune # PPO model name.
learning_rate: 1e-5 #1.41e-5 # Learning rate for PPO.
log_with: "wandb" # Logging method.
batch_size: 16 # Batch size.
mini_batch_size: 1 # Mini-batch size.
gradient_accumulation_steps: 16 # Gradient accumulation steps.
early_stopping: False # Whether to use early stopping.
target_kl: 0.1 # Target KL divergence.
ppo_epochs: 4 # Number of epochs for PPO training.
seed: 0 # Random seed.
init_kl_coef: 0.2 # Initial KL coefficient.
adap_kl_ctrl: True # Whether to adapt KL control.
I monitored each step and found that the generate step takes (30min to 1 hour) more time than the optimization step. This only happens when gradient_checkpointing is enabled otherwise it takes just 5-10 min (for 16 queries).
One unusual observation is, that even when gradient_checkpointing is enabled first step takes only 10 min for the overall process and from the second step it take around one hour. I have checked that the number of query and response tokens are almost the same for both steps.
Can you disable gradient_checkpointing before generating and turn it back on after?
I updated the code for manually disabling and enabling the checkpointing and it does make a lot of difference. Now each step takes 7 minutes on average (generation + optimization). However, there is still a memory spike during the optimization step and I get an OOM error at some steps even after using mini_batch_size=1. Does this mean 40GB VRAM is not enough for LlaMa-2-7B fine-tuning? or there is still room for optimizing the memory?
for epoch, batch in tqdm(enumerate(ppo_trainer.dataloader)):
query_tensor = batch["input_ids"]
ppo_trainer.model.gradient_checkpointing_disable()
response_tensors = ppo_trainer.generate(
query_tensor,
return_prompt=False,
batch_size=3,
# length_sampler=512
**generation_kwargs,
)
ppo_trainer.model.gradient_checkpointing_enable()
batch["response"] = tokenizer.batch_decode(response_tensors, skip_special_tokens=True)
texts = [q + r for q, r in zip(batch["query"], batch["response"])]
inputs = tokenizer(texts, max_length=2048,padding=True, truncation=True, return_tensors="pt").to(base_reward_model.device)
rewards = compute_reward_score(inputs,base_reward_model,conf)
#Run PPO step
stats = ppo_trainer.step(query_tensor, response_tensors, rewards)
rewards = [r.float() if r.dtype == torch.bfloat16 else r for r in rewards]
if epoch%conf.log_step==0:
ppo_trainer.log_stats(stats, batch, rewards)
if epoch > 0 and epoch%conf.save_steps==0:
ppo_trainer.save_pretrained(save_dir + f"/checkpoint_{epoch}")
Are you using quantization and Lora with PEFT? This could help reducing the memory footprint.
Yes I am already using QLora with the following config
dtype = torch.bfloat16
lora_config = LoraConfig(
r=64,
lora_alpha=16,
lora_dropout=0.1,
bias="none",
task_type="CAUSAL_LM",
target_modules=["q_proj",
"down_proj",
"gate_proj",
"o_proj",
"k_proj",
"v_proj",
"up_proj"
]
)
model_args = {
"torch_dtype": dtype,
"quantization_config": BitsAndBytesConfig(
load_in_4bit=True,
bnb_4bit_quant_type="nf4",
bnb_4bit_compute_dtype=dtype,
bnb_4bit_use_double_quant=True,
),
"cache_dir": CACHE_DIR,
"device_map": device_map,
"load_in_4bit":True
}
I think with PEFT you should be able to run a 7B with 40GB. cc @younesbelkada
I am using an Open Assitant Dataset with a max_token size of 2048. May be that's the problem?
I updated the code for manually disabling and enabling the checkpointing and it does make a lot of difference. Now each step takes 7 minutes on average (generation + optimization). However, there is still a memory spike during the optimization step and I get an OOM error at some steps even after using
mini_batch_size=1. Does this mean 40GB VRAM is not enough for LlaMa-2-7B fine-tuning? or there is still room for optimizing the memory?for epoch, batch in tqdm(enumerate(ppo_trainer.dataloader)): query_tensor = batch["input_ids"] ppo_trainer.model.gradient_checkpointing_disable() response_tensors = ppo_trainer.generate( query_tensor, return_prompt=False, batch_size=3, # length_sampler=512 **generation_kwargs, ) ppo_trainer.model.gradient_checkpointing_enable() batch["response"] = tokenizer.batch_decode(response_tensors, skip_special_tokens=True) texts = [q + r for q, r in zip(batch["query"], batch["response"])] inputs = tokenizer(texts, max_length=2048,padding=True, truncation=True, return_tensors="pt").to(base_reward_model.device) rewards = compute_reward_score(inputs,base_reward_model,conf) #Run PPO step stats = ppo_trainer.step(query_tensor, response_tensors, rewards) rewards = [r.float() if r.dtype == torch.bfloat16 else r for r in rewards] if epoch%conf.log_step==0: ppo_trainer.log_stats(stats, batch, rewards) if epoch > 0 and epoch%conf.save_steps==0: ppo_trainer.save_pretrained(save_dir + f"/checkpoint_{epoch}")
I got the same error, I ran my script on multi-GPUs and I can not disable the checking point.
@harrison4ride To resolve the OOM error I increased the vRAM (40GB + 40 GB) and now I am facing the same issue again. It's taking more than 1 hour for the generation step and gradient_checkpointing_disable doesn't have any impact.
@harrison4ride To resolve the OOM error I increased the vRAM (40GB + 40 GB) and now I am facing the same issue again. It's taking more than 1 hour for the generation step and
gradient_checkpointing_disabledoesn't have any impact.
What is your input_min_text_length and input_max_text_length? I think the input_max_text_length have great impact on memory usage.
do you mean max_new_token? I am setting max_length to 2048 out of which 450 tokens are new generated token and reset are query tokens.
FYI I disabled the gradient checkpointing manually by using the below command, then also its taking 90 minutes to generate the response for 16 queries. This problem only occurs when using multi-gpu.
base_model = prepare_model_for_kbit_training(base_model,use_gradient_checkpointing=False)
In my experience, 40GB VRAM is not enough to train LLAMA-2-7B with 2048 tokens. Hence I am using 2 A100 (40GB)
With below config its possible to train on multiple GPU and it also allow to disable gradient checkpointing:
max_memory = get_balanced_memory(model,
# low_zero=True,
dtype=dtype,
no_split_module_classes = ['LlamaDecoderLayer'],
max_memory= {0: '20GIB', 1: '40GIB'},
)
device_map = infer_auto_device_map(
model,
max_memory=max_memory,
# Manually set the modules to not split based on the model.
# The models' say but it's hard to figure out at this stage without doing it manually.
no_split_module_classes=["LlamaDecoderLayer", "lm_head"],
dtype=dtype,
)
# As per the peft instructions, make sure the lm_head is on gpu 0.
# This works for Llama, not sure what to set for pythia models.
device_map["lm_head"] = 0
model_args["device_map"] = device_map
Also check https://github.com/huggingface/trl/issues/610