-
Notifications
You must be signed in to change notification settings - Fork 5.1k
[Feature] Optimizations for JPEG input on NVIDIA GPU #19749
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
Merged
Merged
Changes from all commits
Commits
Show all changes
2 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -86,6 +86,7 @@ | |
| from torch import nn | ||
| from torch.library import Library | ||
| from torch.utils._contextlib import _DecoratorContextManager | ||
| from torchvision.io import decode_jpeg | ||
| from typing_extensions import Literal | ||
|
|
||
| from sglang.srt.environ import envs | ||
|
|
@@ -763,64 +764,109 @@ class ImageData: | |
| max_dynamic_patch: Optional[int] = None | ||
|
|
||
|
|
||
| image_extension_names = (".png", ".jpg", ".jpeg", ".webp", ".gif") | ||
|
Collaborator
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. we need a
Collaborator
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. got it |
||
|
|
||
|
|
||
| def is_jpeg_with_cuda(image_bytes: bytes = b"", gpu_image_decode: bool = True) -> bool: | ||
| """ | ||
| Check three conditions: | ||
| 1. whether CUDA is available. | ||
| 2. whether input is recognized as JPEG. | ||
| 3. whether GPU image decode is enabled (some models such as CPM forcibly disable this). | ||
| """ | ||
| if not is_cuda() or not gpu_image_decode: | ||
| return False | ||
| if image_bytes != b"": | ||
| return image_bytes.startswith(b"\xff\xd8") and image_bytes.endswith(b"\xff\xd9") | ||
| return False | ||
|
|
||
|
|
||
| def _load_image( | ||
| image_bytes: bytes = b"", | ||
| image_file: str = "", | ||
| gpu_image_decode: bool = True, | ||
| ) -> Union[torch.Tensor, Image.Image]: | ||
| """ | ||
| Try to decode JPEG with nvJPEG on GPU and return a torch device tensor, | ||
| otherwise fallback to decode with PIL on CPU and return a PIL Image. | ||
| Keep the fallback path since nvJPEG may fail on some JPEG images that are not strictly compliant with the standard, while PIL is more tolerant. | ||
| """ | ||
| if image_file != "": | ||
| image_bytes = get_image_bytes(image_file) | ||
| if is_jpeg_with_cuda(image_bytes, gpu_image_decode): | ||
| try: | ||
| encoded_image = torch.frombuffer(image_bytes, dtype=torch.uint8) | ||
| image_tensor = decode_jpeg(encoded_image, device="cuda") | ||
| return image_tensor | ||
| except Exception as e: | ||
| logger.warning( | ||
| f"Failed to decode JPEG on GPU, falling back to CPU. Error: {e}" | ||
| ) | ||
| return Image.open(BytesIO(image_bytes)) | ||
|
|
||
|
|
||
| def load_image( | ||
| image_file: Union[Image.Image, str, ImageData, bytes], | ||
| ) -> tuple[Image.Image, tuple[int, int]]: | ||
| gpu_image_decode: bool = True, | ||
| ) -> tuple[Union[torch.Tensor, Image.Image], Optional[tuple[int, int]]]: | ||
| """ | ||
| Load image from multiple input formats, including: | ||
| ImageData, PIL Image, bytes, URL, file path, or base64 string. | ||
| """ | ||
| if isinstance(image_file, ImageData): | ||
| image_file = image_file.url | ||
|
|
||
| image = image_size = None | ||
| image = None | ||
| image_size: Optional[tuple[int, int]] = None | ||
| if isinstance(image_file, Image.Image): | ||
| image = image_file | ||
| image_size = (image.width, image.height) | ||
| elif isinstance(image_file, bytes): | ||
| image = Image.open(BytesIO(image_file)) | ||
| elif image_file.startswith("http://") or image_file.startswith("https://"): | ||
| timeout = int(os.getenv("REQUEST_TIMEOUT", "3")) | ||
| response = requests.get(image_file, stream=True, timeout=timeout) | ||
| try: | ||
| response.raise_for_status() | ||
| image = Image.open(response.raw) | ||
| image.load() # Force loading to avoid issues after closing the stream | ||
| finally: | ||
| response.close() | ||
| elif image_file.startswith("file://"): | ||
| image_file = unquote(urlparse(image_file).path) | ||
| image = Image.open(image_file) | ||
| elif image_file.lower().endswith(("png", "jpg", "jpeg", "webp", "gif")): | ||
| image = Image.open(image_file) | ||
| elif image_file.startswith("data:"): | ||
| image_file = image_file.split(",")[1] | ||
| image = Image.open(BytesIO(pybase64.b64decode(image_file, validate=True))) | ||
| elif isinstance(image_file, str): | ||
| image = Image.open(BytesIO(pybase64.b64decode(image_file, validate=True))) | ||
| image = _load_image(image_bytes=image_file, gpu_image_decode=gpu_image_decode) | ||
| elif isinstance(image_file, str) and image_file.startswith(("http://", "https://")): | ||
| image = _load_image(image_file=image_file, gpu_image_decode=gpu_image_decode) | ||
| elif isinstance(image_file, str) and image_file.startswith("file://"): | ||
| image = _load_image( | ||
| image_file=unquote(urlparse(image_file).path), | ||
| gpu_image_decode=gpu_image_decode, | ||
| ) | ||
| elif isinstance(image_file, str) and image_file.lower().endswith( | ||
| image_extension_names | ||
| ): | ||
| image = _load_image(image_file=image_file, gpu_image_decode=gpu_image_decode) | ||
| elif isinstance(image_file, str) and image_file.startswith("data:"): | ||
| image = _load_image(image_file=image_file, gpu_image_decode=gpu_image_decode) | ||
| elif isinstance( | ||
| image_file, str | ||
| ): # Other formats, try to decode as base64 by default | ||
| image = _load_image(image_file=image_file, gpu_image_decode=gpu_image_decode) | ||
| else: | ||
| raise ValueError(f"Invalid image: {image_file}") | ||
|
|
||
| return image, image_size | ||
|
|
||
|
|
||
| def get_image_bytes(image_file: Union[str, bytes]): | ||
| def get_image_bytes(image_file: Union[str, bytes]) -> bytes: | ||
| """Normalize various image inputs into raw bytes.""" | ||
| if isinstance(image_file, bytes): | ||
| return image_file | ||
| elif image_file.startswith("http://") or image_file.startswith("https://"): | ||
| if image_file.startswith(("http://", "https://")): | ||
| timeout = int(os.getenv("REQUEST_TIMEOUT", "3")) | ||
| response = requests.get(image_file, timeout=timeout) | ||
| return response.content | ||
| elif image_file.startswith("file://"): | ||
| image_file = unquote(urlparse(image_file).path) | ||
| with open(image_file, "rb") as f: | ||
| return f.read() | ||
| elif image_file.lower().endswith(("png", "jpg", "jpeg", "webp", "gif")): | ||
yhyang201 marked this conversation as resolved.
Show resolved
Hide resolved
|
||
| try: | ||
| response.raise_for_status() | ||
| result = response.content | ||
| finally: | ||
| response.close() | ||
| return result | ||
| if image_file.startswith(("file://", "/")): | ||
| with open(image_file, "rb") as f: | ||
| return f.read() | ||
| elif image_file.startswith("data:"): | ||
| image_file = image_file.split(",")[1] | ||
| if isinstance(image_file, str) and image_file.startswith("data:"): | ||
| _, encoded = image_file.split(",", 1) | ||
| return pybase64.b64decode(encoded, validate=True) | ||
| if isinstance(image_file, str): | ||
| return pybase64.b64decode(image_file, validate=True) | ||
| elif isinstance(image_file, str): | ||
| return pybase64.b64decode(image_file, validate=True) | ||
| else: | ||
| raise NotImplementedError(f"Invalid image: {image_file}") | ||
| raise NotImplementedError(f"Invalid image: {image_file}") | ||
|
|
||
|
|
||
| def _normalize_video_input( | ||
|
|
||
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.