Fix: Update torch.cuda.amp to torch.amp to Resolve Deprecation Warning
Description
This PR addresses issue #13226 which raises a FutureWarning due to the deprecation of torch.cuda.amp as of PyTorch 2.4. This replaces all instances of torch.cuda.amp with torch.amp to resolve the warning.
Key Changes
- Replaced all instances of
torch.cuda.amp.autocastwithtorch.amp.autocast('cuda', ...). - Replaced
torch.cuda.amp.GradScalerwithtorch.amp.GradScaler('cuda').
Steps to Reproduce and Testing
To verify the fix, I used a custom test script that was previously showing the deprecation warning. The following tests were performed:
- Test Script: I ran a test script using YOLOv5 and confirmed that the deprecation warning no longer appears after applying the changes.
- Warning Before Fix: The screenshot below shows the deprecation warning when installing the model directly from the repo.
- Warning After Fix: After applying the fix, the warning no longer appears, as shown in the second screenshot.
Test Script:
The test script used for verification:
import torch
from pathlib import Path
import cv2
import numpy as np
from PIL import Image
# model = torch.hub.load('ultralytics/yolov5', 'yolov5') # latest model causes warning
model = torch.hub.load('./YOLOV5', 'yolov5n', source='local', weights_only=True)
model.eval()
cap = cv2.VideoCapture(0)
while True:
ret, frame = cap.read()
if not ret:
break
results = model(frame)
for det in results.xyxy[0]:
x1, y1, x2, y2, conf, cls = det.tolist()
label = f'{results.names[int(cls)]} {conf:.2f}'
print(label)
cv2.putText(frame, label, (int(x1), int(y1) - 10), cv2.FONT_HERSHEY_SIMPLEX, 0.5, (0, 255, 0), 2 )
render_frame = results.render()[0]
cv2.imshow('Detection', render_frame)
if cv2.waitKey(1) & 0xFF == ord('q'):
break
cap.release()
cv2.destroyAllWindows()
Screenshots
Warning Before the Change:
This screenshot shows the deprecation warning before the fix.
Warning After the Change:
This screenshot shows that the warning is no longer present after applying the fix.
Purpose & Impact
- Improved Compatibility: Ensures that the code is compatible with PyTorch 2.4 and newer versions, reducing future issues.
- Performance: Leverages the latest improvements in automatic mixed precision (AMP) for better performance on CUDA-enabled devices.
Additional Comments
Since the original PR #13244 has been inactive, I have submitted this new PR with the updated changes to resolve the issue #13226 .
π οΈ PR Summary
Made with β€οΈ by Ultralytics Actions
π Summary
Updated the PyTorch mixed precision (AMP) method usage to align with the latest torch.amp standards for better compatibility and future-proofing.
π Key Changes
- Replaced
torch.cuda.ampusages withtorch.ampacross various files:val.py,common.py,train.py,segment/train.py, andutils/autobatch.py.
- Updated
autocastandGradScalermethods to specify"cuda"explicitly.
π― Purpose & Impact
- Consistency with PyTorch: Ensures compatibility with the latest PyTorch API, as
torch.ampis more generic and future-focused compared totorch.cuda.amp. - Enhanced Stability: Reduces potential deprecation or compatibility issues in future PyTorch releases.
- Improved Usability: Explicitly specifying
"cuda"helps clarify intent and avoids potential confusion, particularly for non-CPU environments. - Seamless Transition: Existing functionality remains unchanged for users, ensuring continuity without disruptions. π
All Contributors have signed the CLA. β
Posted by the CLA Assistant Lite bot.
π Hello @Bala-Vignesh-Reddy, thank you for submitting an ultralytics/yolov5 π PR! To ensure a seamless integration of your work, please review the following checklist:
- β Define a Purpose: Clearly explain the purpose of your fix or feature in your PR description, and link to any relevant issues. Ensure your commit messages are clear, concise, and adhere to the project's conventions.
- β
Synchronize with Source: Confirm your PR is synchronized with the
ultralytics/yolov5mainbranch. If it's behind, update it by clicking the 'Update branch' button or by runninggit pullandgit merge mainlocally. - β Ensure CI Checks Pass: Verify all Ultralytics Continuous Integration (CI) checks are passing. If any checks fail, please address the issues.
- β Update Documentation: Update the relevant documentation for any new or modified features.
- β Add Tests: If applicable, include or update tests to cover your changes, and confirm that all tests are passing.
- β Sign the CLA: Please ensure you have signed our Contributor License Agreement (CLA) if this is your first Ultralytics PR by writing "I have read the CLA Document and I sign the CLA" in a new message.
- β Minimize Changes: Limit your changes to the minimum necessary for your bug fix or feature addition. "It is not daily increase but daily decrease, hack away the unessential. The closer to the source, the less wastage there is." β Bruce Lee
π οΈ Notes and Feedback:
Your PR for replacing all instances of torch.cuda.amp with torch.amp, as detailed in your description and diff, looks well-crafted and effectively aligns YOLOv5 with the most current torch.amp standards. Ensuring compatibility with PyTorch 2.4 is crucial for robustness, and we appreciate the inclusion of test scripts and comparison screenshots! π
If possible, please provide a minimum reproducible example (MRE) for broader validation, including any specific configurations or edge cases you've tested this with. This will help other contributors and engineers verify the fixes more effectively. π
For additional guidance, you can refer to our Contributing Guide and CI Documentation.
π Next Steps:
An Ultralytics engineer will review your PR in detail soon. If there are any updates or changes on your end, donβt hesitate to update the PR. Thank you again for contributing to Ultralytics! π
I have read the CLA Document and I sign the CLA
May resolve #13226
@Bala-Vignesh-Reddy please review and resolve failing CI tests. Thank you!
@glenn-jocher I have reviewed and resolved.. and all the CI tests are passed succesfully.. Looking forward for your response.. Thank you!
@glenn-jocher any updates? Thank You!
@glenn-jocher have a look at this pr.. and review the pr asap..
@Bala-Vignesh-Reddy this is a good PR but there is too much duplication of code. The check should be done once per file at the top after import. Can you please make this change? Thank you!
@glenn-jocher refactored the code and check for the version is done at the top.. Have a look at it and tell me if any changes needed.. Thank you!!
@glenn-jocher any further updates..? Thank You!!
π Hello there! We wanted to let you know that we've decided to close this pull request due to inactivity. We appreciate the effort you put into contributing to our project, but unfortunately, not all contributions are suitable or aligned with our product roadmap.
We hope you understand our decision, and please don't let it discourage you from contributing to open source projects in the future. We value all of our community members and their contributions, and we encourage you to keep exploring new projects and ways to get involved.
For additional resources and information, please see the links below:
- Docs: https://docs.ultralytics.com
- HUB: https://hub.ultralytics.com
- Community: https://community.ultralytics.com
Thank you for your contributions to YOLO π and Vision AI β