[BUG] access the gradient while tranining
Describe the bug A clear and concise description of what the bug is. I am training a model using accelerator with DeepSpeed stage '1,2' within the training loop I need to access the gradient to mask some of the embedding gradient. I am using safe_get_full_grad function as in docs.
To Reproduce Steps to reproduce the behavior: ` accelerator.backward(loss) if accelerator.distributed_type == DistributedType.DEEPSPEED: for n_param, param in accelerator.deepspeed_engine_wrapped.engine.named_parameters(): if "embed" in n_param: grad = safe_get_full_grad(param) grad[embedding_mask] = 0.0 break
update parameters
optimizer.step() ` 4. Error ValueError('Gradients are only available after backward and before engine step.')
Expected behavior I expect to get an access to the gradient
ds_report output
Please run ds_report to give us details about your setup.
Screenshots
If applicable, add screenshots to help explain your problem.
System info (please complete the following information):
- OS: [e.g. Ubuntu 20.04]
- GPU count and types x2 A100s
- Python version
- Any other relevant info about your setup
Launcher context
Are you launching your experiment with the deepspeed launcher, MPI, or something else?
accelerate launcher
Docker context Are you using a specific docker image that you can share? NO
Additional context Add any other context about the problem here.
Another function safe_set_full_grad
may help.
However, I cannot solve my problem too. I am doing the same thing, but my log show me that
Trying to get gradient through DeepSpeed engine for input embeddings
DeepSpeed engine method failed for input embeddings: Gradients are only available immediately after backward and before engine step
Failed to apply mask to input embeddings
Trying to get gradient through DeepSpeed engine for output embeddings
DeepSpeed engine method failed for output embeddings: Gradients are only available immediately after backward and before engine step
Here is my code.
def reset_embeddings(self, model, engine=None):
"""在反向传播后应用梯度掩码"""
def apply_mask_to_grad(param, mask, param_name):
try:
print(f"Trying to get gradient through DeepSpeed engine for {param_name}")
# 通过 engine 获取参数的完整梯度
# param_id = engine.param_id(param)
# 将梯度乘以掩码
grad_param = deepspeed.utils.safe_get_full_grad(param)
grad_param*=mask
deepspeed.utils.safe_set_full_grad(param, grad_param)
return True
except Exception as e:
print(f"DeepSpeed engine method failed for {param_name}: {str(e)}")
return False
with torch.no_grad():
if self.args.lora_enable:
for name, param in model.named_parameters():
if "embed_tokens" in name:
if not apply_mask_to_grad(param, self.input_embeds_grad_mask, "input embeddings"):
print(f"Failed to apply mask to input embeddings")
elif "lm_head" in name:
if not apply_mask_to_grad(param, self.output_embeds_grad_mask, "output embeddings"):
print(f"Failed to apply mask to output embeddings")
else:
input_embed = model.get_input_embeddings().weight
output_embed = model.get_output_embeddings().weight
if not apply_mask_to_grad(input_embed, self.input_embeds_grad_mask, "input embeddings"):
print(f"Failed to apply mask to input embeddings")
if not apply_mask_to_grad(output_embed, self.output_embeds_grad_mask, "output embeddings"):
print(f"Failed to apply mask to output embeddings")
Hi, I have solved the problem. Here are some information may help you.
Step1 Change your config to enable grad_hooks.
Here is my zero2.json
{
"fp16": {
"enabled": "auto",
"loss_scale": 0,
"loss_scale_window": 1000,
"initial_scale_power": 16,
"hysteresis": 2,
"min_loss_scale": 1
},
"bf16": {
"enabled": "auto"
},
"train_micro_batch_size_per_gpu": "auto",
"train_batch_size": "auto",
"gradient_accumulation_steps": "auto",
"zero_optimization": {
"stage": 2,
"overlap_comm": true,
"contiguous_gradients": true,
"sub_group_size": 1e9,
"reduce_bucket_size": "auto",
"zero_quantized_weights": false,
"zero_quantized_gradients": false,
"param_persistence_threshold": 0,
"grad_hooks": true,
"pin_gradients": true
}
}
Step2 Make sure that what param you want to set is requires_grad_
I think here may different from torch
def training_step(self, model, inputs):
# 在每个训练步骤之前确保嵌入层的梯度可用
# 添加我们的特殊 token 相关逻辑
if self.train_special_token:
input_embed = self.model.get_input_embeddings().weight
output_embed = self.model.get_output_embeddings().weight
# 确保参数需要梯度
input_embed.requires_grad_(True)
output_embed.requires_grad_(True)
# 调用父类的 training_step
return super().training_step(model, inputs)
"grad_hooks": true,
"pin_gradients": true } }
@JimmyMa99 ,the above two configurations are no-ops for DeepSpeed, so I am surprised to see them recommended. Can you share your observations? Please note that ZeRO-2 normally uses hooks to implement gradient partitioning.
Otherwise, your solution above seems correct. So, I will close this issue for now.
i am having a similar issue and i couldnt use the solution above, perhaps its only applied on Zero1?
pydantic.v1.error_wrappers.ValidationError: 1 validation error for DeepSpeedZeroConfig
grad_hooks
extra fields not permitted (type=value_error.extra)
python-BaseException
i am having a similar issue and i couldnt use the solution above, perhaps its only applied on Zero1?
@GonyRosenman, as I mentioned earlier, those options are not supported. If your issue is the same as the original in this post, then please see the following docs:
- https://deepspeed.readthedocs.io/en/latest/zero3.html#debugging
- https://deepspeed.readthedocs.io/en/latest/zero3.html#modifying-partitioned-states
Hi, I have the same problem. I want to modify arguments in on_pre_optimizer_step callback in transformers.Trainer, looking at the code it is called in-between of backward and step. Can we reopen this issue? I also don't see anything in the links @tjruwase provided. Could you please direct me to where the solution is in those links?
@JimmyMa99 hi. You solution doesn't work for me, I get the same error as @GonyRosenman.
I also have the same problem when trying to get the gradients either right before step (this line -- https://github.com/huggingface/transformers/blob/d5b81e1ca173efb102649446249e3f2669b98410/src/transformers/trainer.py#L2577) or right after backward (this line -- https://github.com/huggingface/transformers/blob/d5b81e1ca173efb102649446249e3f2669b98410/src/transformers/trainer.py#L3702)
@ummagumm-a, can you please clarify why you are unable to use safe_set_full_grad?
https://deepspeed.readthedocs.io/en/latest/zero3.html#deepspeed.utils.safe_set_full_grad
@tjruwase now I am not trying to use set, only get. Since I first need to get the gradients before zeroing out some of them and setting back.
when trying to use safe_get_full_grad, I get ValueError: Gradients are only available immediately after backward and before engine step. I tried three places (i wrote earlier), ensuring (hopefully) that they are in between of these two operations.
@ummagumm-a, thanks for the clarification. Are you able to provide full repro steps? I realize you previously mentioned the code lines that you modified, but it would be a lot more help full if you provided code and scripts to reproduce the error on our side.
@tjruwase I will try to compile a small repro tomorrow, thanks for your help)
@tjruwase https://gist.github.com/ummagumm-a/feef6e25771e4fd9dc3a90d8449e343f
@ummagumm-a, thanks. I will give it a try
@tjruwase https://gist.github.com/ummagumm-a/feef6e25771e4fd9dc3a90d8449e343f
Thanks, I was able to repro with your example. I discovered that the problem is because accelerate runs the optimizer in the backward pass of the deepspeed plugin. https://github.com/huggingface/accelerate/blob/200c9eb7833cfa505907f6f224ebf5a275aa6d92/src/accelerate/utils/deepspeed.py#L255
It seems that the callback needs to be called in accelerate rather than in transformers.
@tjruwase thanks for your help! I think I saw somewhere that either accelerate team or deepspeed team plan to separate these two operations to avoid such issues - seems like a good feature to wait for.
Also, the link that you attached on accelerate brings me to an 'empty' cite . Is there an alternative callback in accelerate that I can use? The ideal option is to do it without going into the code of either
accelerate or transformers or deepspeed for a clean solution (I mean without patching those repos). I will be very grateful for any suggestion on how to do it!)
@ummagumm-a, I have fixed the url typo; apologies for that.
In terms of separate the two operations, it might be better to open an accelerate ticket since the change is needed on their side. Feel free to tag me on the ticket.
I found out that this feature works (surprisingly) with zero-stage 3. You could try that in case the expected perf loss is suitable for your scenario.
@tjruwase zero-3 indeed doesn't give any error, and seems to train well. thanks!
Yes! This issue only happen when using zero-2.
Although zero-3 doesn't give any error, if using on_pre_optimizer_step(), still it is called after deepspeed engine's step(). My workaround is to override the Trainer's training_step(), add custom code between self.accelerator.deepspeed_engine_wrapped.engine.backward(loss, **kwargs) and self.accelerator.deepspeed_engine_wrapped.engine.step().