-
Notifications
You must be signed in to change notification settings - Fork 337
feat(visual): reserve ViT worst-case activation memory #1378
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
Open
sufubao
wants to merge
1
commit into
ModelTC:main
Choose a base branch
from
sufubao:vit-worst-case-mem-reserve
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
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
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,80 @@ | ||
| import math | ||
| from typing import List, Tuple | ||
| import torch | ||
| from lightllm.server.router.dynamic_prompt.shared_arr import SharedInt | ||
| from lightllm.utils.envs_utils import get_unique_server_name | ||
| from lightllm.utils.log_utils import init_logger | ||
|
|
||
| logger = init_logger(__name__) | ||
|
|
||
|
|
||
| def get_vit_reserved_shm_name(device_id: int, global_rank: int) -> str: | ||
| return f"{get_unique_server_name()}_vit_reserved_mem_d{device_id}_r{global_rank}" | ||
|
|
||
|
|
||
| def publish_vit_reserved_mem(device_id: int, global_rank: int, reserved_bytes: int) -> None: | ||
| """Visual rank writes its held worst-case reservation (bytes) for cross-process discovery.""" | ||
| shm = SharedInt(get_vit_reserved_shm_name(device_id, global_rank)) | ||
| shm.set_value(int(reserved_bytes)) | ||
|
|
||
|
|
||
| def read_vit_reserved_mem_for_device(args, device_id: int) -> int: | ||
| """Router side: sum reservations of all visual ranks placed on `device_id`. Diagnostic only.""" | ||
| if getattr(args, "disable_vision", False) or not getattr(args, "enable_multimodal", False): | ||
| return 0 | ||
| gpu_ids = getattr(args, "visual_gpu_ids", None) or [] | ||
| total = 0 | ||
| # assumes global_rank == index into visual_gpu_ids (matching how visual ranks call publish_vit_reserved_mem) | ||
| for global_rank, dev in enumerate(gpu_ids): | ||
| if dev == device_id: | ||
| total += int(SharedInt(get_vit_reserved_shm_name(dev, global_rank)).get_value()) | ||
| return total | ||
|
|
||
|
|
||
| def reserve_guard_tensor(device_id: int, reserved_gb: float) -> Tuple[torch.Tensor, int]: | ||
| """Allocate and HOLD a guard tensor of `reserved_gb` GB so the allocator high-water mark persists. | ||
| Returns (tensor, nbytes). The caller MUST keep a reference to the tensor.""" | ||
| nbytes = int(reserved_gb * 1024 ** 3) | ||
| guard = torch.empty(nbytes, dtype=torch.uint8, device=f"cuda:{device_id}") | ||
| return guard, nbytes | ||
|
|
||
|
|
||
| def compute_qwen_worst_case_grid( | ||
| batch_size: int, | ||
| max_image_pixels: int, | ||
| max_image_token_count: int, | ||
| patch_size: int, | ||
| temporal_patch_size: int, | ||
| in_channels: int, | ||
| spatial_merge_size: int, | ||
| ) -> Tuple[Tuple[int, int], List[List[int]]]: | ||
| """Pure shape math for the Qwen-VL worst case. | ||
|
|
||
| Returns ((total_patches, row_width), grid_thw) where pixel_values has shape | ||
| (total_patches, row_width) and grid_thw is one [t, h, w] triple per dummy image. | ||
| Bounds each image by BOTH the per-image token cap and pixel cap (whichever is tighter), | ||
| using the smallest square grid (sides multiples of spatial_merge_size) whose patch count | ||
| is >= that cap. The side is rounded UP so the probe is an upper bound on the largest valid | ||
| request and never under-reserves (a square floor could undershoot, e.g. isqrt(32768)=181 | ||
| -> 180x180 = 32400 patches < the 32768-patch cap). | ||
|
|
||
| Assumes valid inputs (max_image_token_count > 0 and max_image_pixels >= (patch_size * | ||
| spatial_merge_size)**2); smaller budgets are clamped up to a single spatial_merge_size tile. | ||
| """ | ||
| spatial_merge_unit = spatial_merge_size * spatial_merge_size | ||
| patches_by_tokens = max_image_token_count * spatial_merge_unit | ||
| patches_by_pixels = max_image_pixels // (patch_size * patch_size) | ||
| max_patches = max(1, min(patches_by_tokens, patches_by_pixels)) | ||
|
|
||
| side = int(math.isqrt(max_patches)) | ||
| if side * side < max_patches: | ||
| side += 1 # ceil(sqrt) so side*side >= max_patches (never undershoot) | ||
| if side % spatial_merge_size: | ||
| side += spatial_merge_size - (side % spatial_merge_size) # round up to a merge-unit multiple | ||
| side = max(side, spatial_merge_size) # never smaller than one merge unit | ||
|
|
||
| grid_h = grid_w = side | ||
| row_width = in_channels * temporal_patch_size * patch_size * patch_size | ||
| total_patches = grid_h * grid_w * batch_size | ||
| grid_thw = [[1, grid_h, grid_w] for _ in range(batch_size)] | ||
| return (total_patches, row_width), grid_thw | ||
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
Oops, something went wrong.
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.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
During concurrent startup of the LLM worker and the visual worker, the LLM worker may call
read_vit_reserved_mem_for_devicebefore the visual worker has initialized and published its reserved memory viapublish_vit_reserved_mem. In this case,SharedIntwill raise an exception (such asFileNotFoundErrororValueError) because the shared memory segment does not exist yet, causing the LLM worker to crash during startup. Wrapping the lookup in atry...exceptblock ensures robust defensive programming and prevents startup crashes.