Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

How to close the amp? #12903

Closed
1 task done
Git376364743 opened this issue Apr 10, 2024 · 10 comments
Closed
1 task done

How to close the amp? #12903

Git376364743 opened this issue Apr 10, 2024 · 10 comments
Labels
question Further information is requested Stale

Comments

@Git376364743
Copy link

Search before asking

Question

  1. I want to add HWD module in yolov5-7.0, the changed yolovs.yaml file can be run in yolo.py but not in train.py file, please help me to see what causes the error, thanks!
    RuntimeError: Input type (torch.cuda.HalfTensor) and weight type (torch.cuda.FloatTensor) should be the same

  2. In other forums some people answered that it can be run after turning off AMP, please tell me how to turn off AMP!

Additional

No response

@Git376364743 Git376364743 added the question Further information is requested label Apr 10, 2024
Copy link
Contributor

👋 Hello @Git376364743, thank you for your interest in YOLOv5 🚀! Please visit our ⭐️ Tutorials to get started, where you can find quickstart guides for simple tasks like Custom Data Training all the way to advanced concepts like Hyperparameter Evolution.

If this is a 🐛 Bug Report, please provide a minimum reproducible example to help us debug it.

If this is a custom training ❓ Question, please provide as much information as possible, including dataset image examples and training logs, and verify you are following our Tips for Best Training Results.

Requirements

Python>=3.8.0 with all requirements.txt installed including PyTorch>=1.8. To get started:

git clone https://github.com/ultralytics/yolov5  # clone
cd yolov5
pip install -r requirements.txt  # install

Environments

YOLOv5 may be run in any of the following up-to-date verified environments (with all dependencies including CUDA/CUDNN, Python and PyTorch preinstalled):

Status

YOLOv5 CI

If this badge is green, all YOLOv5 GitHub Actions Continuous Integration (CI) tests are currently passing. CI tests verify correct operation of YOLOv5 training, validation, inference, export and benchmarks on macOS, Windows, and Ubuntu every 24 hours and on every commit.

Introducing YOLOv8 🚀

We're excited to announce the launch of our latest state-of-the-art (SOTA) object detection model for 2023 - YOLOv8 🚀!

Designed to be fast, accurate, and easy to use, YOLOv8 is an ideal choice for a wide range of object detection, image segmentation and image classification tasks. With YOLOv8, you'll be able to quickly and accurately detect objects in real-time, streamline your workflows, and achieve new levels of accuracy in your projects.

Check out our YOLOv8 Docs for details and get started with:

pip install ultralytics

@glenn-jocher
Copy link
Member

Hello! 😊 It seems like you're facing a dtype mismatch issue when integrating a custom module into YOLOv5, and you're interested in turning off Automatic Mixed Precision (AMP) as a potential solution.

For disabling AMP in your training, you can adjust the --amp command-line argument when running train.py. By default, AMP is enabled for efficiency, but you can turn it off by setting this argument to False. Here's how you can modify your training command:

python train.py --img 640 --batch 16 --epochs 3 --data dataset.yaml --weights yolov5s.pt --amp False

This command assumes you're training with the default settings but with AMP explicitly turned off. Keep in mind, disabling AMP might increase memory usage and potentially decrease training speed, so monitor performance closely.

Remember, modifications like adding custom modules might require additional adjustments, especially regarding tensor types, to ensure compatibility throughout your model.

If further issues arise, or if you have additional questions, feel free to reach out! Happy coding!

@Git376364743
Copy link
Author

@glenn-jocher Thanks for your reply, but I found that yolov5-master doesn't have the amp function, and I get an error in the train command with --amp False: "train.py: error: unrecognized arguments: --amp False", please give me another solution!

@glenn-jocher
Copy link
Member

Hello! 😊 It looks like there was some confusion regarding the --amp option. My apologies for that. If you're looking to control the precision handling in your YOLOv5 training and can't find an AMP toggle, it's likely because AMP is managed internally and doesn't have a direct command-line switch for disabling in the version of YOLOv5 you are using.

One way to work around precision mismatches without a specific AMP toggle is to ensure all your custom module's tensors and weights are set to the appropriate dtype (e.g., .float() for FloatTensor) explicitly within your module's code. This can help avoid type mismatch issues when AMP is implicitly applied.

If you're facing a specific error due to tensor type mismatches, a code adjustment like the following within your custom module might help:

class MyCustomModule(nn.Module):
    def __init__(self):
        super(MyCustomModule, self).__init__()
        # Your initialization code

    def forward(self, x):
        x = x.float()  # Ensure input is FloatTensor
        # Your forward pass code
        return x

Double-check to ensure all inputs and operations inside your custom module are compatible with floating-point operations. If problems persist, please share more specifics about the mismatch or error for further assistance. Happy to help!

@Git376364743
Copy link
Author

@glenn-jocher Thank you for your answer, but I followed the method and still could not solve the problem "RuntimeError: input type (torch.cuda.HalfTensor) and weight type (torch.cuda.FloatTensor) should be same". Here is the code I referenced that I wanted to incorporate:

class HWD(nn.Module):
def init(self, in_ch, out_ch):
super(HWD, self).init()
from pytorch_wavelets import DWTForward
self.wt = DWTForward(J=1, mode='zero', wave='haar')
self.conv = Conv(in_ch * 4, out_ch, 1, 1)

def forward(self, x):
    x = x.float()
    yL, yH = self.wt(x)
    y_HL = yH[0][:, :, 0, ::]
    y_LH = yH[0][:, :, 1, ::]
    y_HH = yH[0][:, :, 2, ::]
    x = torch.cat([yL, y_HL, y_LH, y_HH], dim=1)
    x = self.conv(x)
    x = x.float()

    return x

Here is the structure of my yolov5s.yaml file:

Parameters

nc: 4 # number of classes
depth_multiple: 0.33 # model depth multiple
width_multiple: 0.50 # layer channel multiple
anchors:

  • [10, 13, 16, 30, 33, 23] # P3/8
  • [30, 61, 62, 45, 59, 119] # P4/16
  • [116, 90, 156, 198, 373, 326] # P5/32

YOLOv5 v6.0 backbone

backbone:

[from, number, module, args]

[
[-1, 1, Conv, [64, 6, 2, 2]], # 0-P1/2
[-1, 1, Conv, [128, 3, 2]], # 1-P2/4
[-1, 3, C3, [128]],
[-1, 1, Conv, [256, 3, 2]], # 3-P3/8
[-1, 6, C3, [256]],
[-1, 1, Conv, [512, 3, 2]], # 5-P4/16
[-1, 9, C3, [512]],
[-1, 1, HWD, []], # 7-P5/32
[-1, 3, C3, [1024]],
[-1, 1, SPPF, [1024, 5]], # 9
]

YOLOv5 v6.0 head

head: [
[-1, 1, Conv, [512, 1, 1]],
[-1, 1, nn.Upsample, [None, 2, "nearest"]],
[[-1, 6], 1, Concat, [1]], # cat backbone P4
[-1, 3, C3, [512, False]], # 13

[-1, 1, Conv, [256, 1, 1]],
[-1, 1, nn.Upsample, [None, 2, "nearest"]],
[[-1, 4], 1, Concat, [1]], # cat backbone P3
[-1, 3, C3, [256, False]], # 17 (P3/8-small)

[-1, 1, Conv, [256, 3, 2]],
[[-1, 14], 1, Concat, [1]], # cat head P4
[-1, 3, C3, [512, False]], # 20 (P4/16-medium)

[-1, 1, Conv, [512, 3, 2]],
[[-1, 10], 1, Concat, [1]], # cat head P5
[-1, 3, C3, [1024, False]], # 23 (P5/32-large)

[[17, 20, 23], 1, Detect, [nc, anchors]], # Detect(P3, P4, P5)

]

Here's all the info, looking forward to your help

@glenn-jocher
Copy link
Member

Hello again! 😊 It looks like the core issue resides in the interaction between the custom HWD module and the input tensor types, particularly when dealing with the DWTForward operation and subsequent operations in mixed precision mode.

To address the "RuntimeError: input type (torch.cuda.HalfTensor) and weight type (torch.cuda.FloatTensor) should be same", let's focus on ensuring consistent tensor types throughout the HWD module, especially considering mixed precision training could be converting tensors into half precision (HalfTensor).

Since AMP can lead to inputs being in half precision, and your custom layer might not support half precision operations directly or might be expecting full precision inputs, you're seeing this inconsistency. However, y = y.float() at the start of your forward method in HWD should convert the input to full precision. If this action alone doesn't resolve the issue, make sure every tensor operation inside your HWD class supports or converts to the expected precision.

One thing you could try is ensuring the output of DWTForward and inputs to self.conv are also explicitly cast to .float() if they aren't already. It looks like you're doing this already, but double-checking these conversions and ensuring all tensors are handled consistently could help. Additionally, consider inspecting the Conv and DWTForward operations to ensure they're not introducing precision discrepancies.

If these suggestions don't resolve the issue, as a workaround, you might need to adjust the training script or the custom module slightly to avoid automatic mixed precision for this particular operation. This could involve a deeper modification to ensure compatibility with mixed precision training environments.

Since your problem does seem quite intricate and possibly specific to the way mixed precision interacts with custom modules and external libraries, further investigation and potentially more detailed debugging might be required to pinpoint the exact cause and solution.

Keep experimenting, and don't hesitate to share more details if you continue facing challenges!

Copy link
Contributor

👋 Hello there! We wanted to give you a friendly reminder that this issue has not had any recent activity and may be closed soon, but don't worry - you can always reopen it if needed. If you still have any questions or concerns, please feel free to let us know how we can help.

For additional resources and information, please see the links below:

Feel free to inform us of any other issues you discover or feature requests that come to mind in the future. Pull Requests (PRs) are also always welcomed!

Thank you for your contributions to YOLO 🚀 and Vision AI ⭐

@github-actions github-actions bot added the Stale label May 12, 2024
@love-whut
Copy link

谢谢你的回答,但是我按照该方法操作,仍然无法解决“RuntimeError:输入类型(torch.cuda.HalfTensor)和权重类型(torch.cuda.FloatTensor)应该相同”的问题。下面是我引用的要合并的代码:

HWD(nn.模块): def init(self, in_ch, out_ch): super(HWD, self).init() from pytorch_wavelets import DWTForward self.wt = DWTForward(J=1, mode='zero', wave='haar') self.conv = Conv(in_ch * 4, out_ch, 1, 1)

def forward(self, x):
    x = x.float()
    yL, yH = self.wt(x)
    y_HL = yH[0][:, :, 0, ::]
    y_LH = yH[0][:, :, 1, ::]
    y_HH = yH[0][:, :, 2, ::]
    x = torch.cat([yL, y_HL, y_LH, y_HH], dim=1)
    x = self.conv(x)
    x = x.float()

    return x

这是我的yolov5s.yaml文件的结构:

参数

NC: 4 # 类数 depth_multiple: 0.33 # 模型深度倍数 width_multiple: 0.50 # 层通道多个锚点:

  • [10, 13, 16, 30, 33, 23] # P3/8
  • [30, 61, 62, 45, 59, 119] # P4/16
  • [116, 90, 156, 198, 373, 326] # 第5/32页

YOLOv5 v6.0 骨干网

骨干:

[从、数字、模块、参数]

[[-1, 1, 转换, [64, 6, 2, 2]], # 0-P1/2 [-1, 1, 转换, [128, 3, 2]], # 1-P2/4 [-1, 3, C3, [128]], [-1, 1, 转换, [256, 3, 2]], # 3-P3/8 [-1, 6, C3, [256]], [-1, 1, 转换, [512, 3, 2]], # 5-P4/16 [-1, 9, C3, [512]], [-1, 1, HWD, []], # 7-P5/32 [-1, 3、C3、[1024]]、[-1、1、SPPF、[1024、5]]、#9 ]

YOLOv5 v6.0 头

头: [ [-1, 1, Conv, [512, 1, 1]], [-1, 1, nn.Upsample, [None, 2, “nearest”]], [[-1, 6], 1, Concat, [1]], # cat 主干 P4 [-1, 3, C3, [512, False]], # 13

[-1, 1, Conv, [256, 1, 1]],
[-1, 1, nn.Upsample, [None, 2, "nearest"]],
[[-1, 4], 1, Concat, [1]], # cat backbone P3
[-1, 3, C3, [256, False]], # 17 (P3/8-small)

[-1, 1, Conv, [256, 3, 2]],
[[-1, 14], 1, Concat, [1]], # cat head P4
[-1, 3, C3, [512, False]], # 20 (P4/16-medium)

[-1, 1, Conv, [512, 3, 2]],
[[-1, 10], 1, Concat, [1]], # cat head P5
[-1, 3, C3, [1024, False]], # 23 (P5/32-large)

[[17, 20, 23], 1, Detect, [nc, anchors]], # Detect(P3, P4, P5)

]

这是所有信息,期待您的帮助

请问您的这个问题解决了嘛?

@glenn-jocher
Copy link
Member

@love-whut hello! 😊 It looks like the issue persists with the tensor type mismatch in your custom HWD module. Here's a suggestion to ensure all components within your module handle the tensor types correctly:

  1. Ensure all tensors are converted to .float() before any operation that might be sensitive to tensor types. This includes operations within DWTForward and before your convolution layer.

Here's a revised version of your forward method:

def forward(self, x):
    x = x.float()  # Convert input to float
    yL, yH = self.wt(x)
    y_HL = yH[0][:, :, 0, :].float()  # Ensure all components are float
    y_LH = yH[0][:, :, 1, :].float()
    y_HH = yH[0][:, :, 2, :].float()
    x = torch.cat([yL, y_HL, y_LH, y_HH], dim=1)
    x = self.conv(x)
    return x
  1. Check the initialization of your Conv layer to ensure it's properly set up to handle the data type. If the convolution layer (self.conv) has parameters initialized in a different data type, it might also cause issues.

If these adjustments don't solve the problem, you might need to look deeper into how DWTForward handles tensor types or consider modifying training settings to avoid mixed precision in parts of your network that handle custom operations.

Keep experimenting, and let me know how it goes!

@github-actions github-actions bot removed the Stale label May 21, 2024
Copy link
Contributor

👋 Hello there! We wanted to give you a friendly reminder that this issue has not had any recent activity and may be closed soon, but don't worry - you can always reopen it if needed. If you still have any questions or concerns, please feel free to let us know how we can help.

For additional resources and information, please see the links below:

Feel free to inform us of any other issues you discover or feature requests that come to mind in the future. Pull Requests (PRs) are also always welcomed!

Thank you for your contributions to YOLO 🚀 and Vision AI ⭐

@github-actions github-actions bot added the Stale label Jun 20, 2024
@github-actions github-actions bot closed this as not planned Won't fix, can't repro, duplicate, stale Jun 30, 2024
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
question Further information is requested Stale
Projects
None yet
Development

No branches or pull requests

3 participants