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

heatmap targets memory optimization #5340

Merged
merged 1 commit into from
Jan 7, 2025
Merged

Conversation

sashankaryal
Copy link
Contributor

@sashankaryal sashankaryal commented Jan 3, 2025

What changes are proposed in this pull request?

When png or jpg heatmaps are decoded, in addition to the overlay image buffer (later converted into GPU optimized ImageBitmap), we also store targets buffers for the tooltip. This targets buffer need not be w x h x 4, and can be of shape w x h.

This optimization should reduce the memory footprint by a factor of 4 when dealing with heatmaps.

How is this patch tested? If it is not, please explain why.

Unit testing, local testing.

import fiftyone as fo
import fiftyone.zoo as foz
import numpy as np
import cv2
import tempfile

d = foz.load_zoo_dataset("quickstart")
d.name = "quickstart-heatmaps"
d.persistent = True

def expand_dataset(dataset, target_num_samples):
    num_doubles = int(np.ceil(np.log2(target_num_samples / len(dataset))))
    with fo.ProgressBar(start_msg="Expanding dataset") as pb:
        for i in pb(list(range(1, num_doubles + 1))):
            if i == num_doubles:
                tmp = dataset[:(target_num_samples - len(dataset))].clone()
            else:
                tmp = dataset.clone()

            dataset.add_collection(tmp, new_ids=True)
            tmp.delete()

expand_dataset(d, len(d)*3)

def generate_random_fo_heatmap(size):
    heatmap = np.random.rand(size, size)
    heatmap = cv2.resize(heatmap, (size, size))
    heatmap = (heatmap * 255).astype(np.uint8)
    return heatmap

def write_heatmap_to_temp(heatmap, is_jpg=False):
    suffix = ".jpg" if is_jpg else ".png"
    with tempfile.NamedTemporaryFile(suffix=suffix, delete=False) as f:
        if is_jpg:
            cv2.imwrite(f.name, heatmap, [int(cv2.IMWRITE_JPEG_QUALITY), 1])
        else:
            cv2.imwrite(f.name, heatmap)
    return f.name

try:
    d.delete_sample_field("heatmap")
except:
    pass

heatmap = generate_random_fo_heatmap(1080)

for s in d:
    heatmap_path = write_heatmap_to_temp(heatmap, is_jpg=True)
    s["heatmap"] = fo.Heatmap(map_path=heatmap_path)
    s.save()

Release Notes

Is this a user-facing change that should be mentioned in the release notes?

  • No. You can skip the rest of this section.
  • Yes. Give a description of this change to be included in the release
    notes for FiftyOne users.

What areas of FiftyOne does this PR affect?

  • App: FiftyOne application changes
  • Build: Build and test infrastructure changes
  • Core: Core fiftyone Python library changes
  • Documentation: FiftyOne documentation changes
  • Other

Summary by CodeRabbit

  • New Features

    • Enhanced canvas decoding with support for different image types
    • Added ability to recast image buffers to mono channel
    • Improved handling of overlay images for various label types (heatmap, segmentation, detection)
  • Bug Fixes

    • Refined canvas and context creation process
    • Improved image data processing for different color formats
  • Tests

    • Added comprehensive test cases for new buffer recasting functionality

@sashankaryal sashankaryal self-assigned this Jan 3, 2025
@sashankaryal sashankaryal requested a review from a team January 3, 2025 20:26
Copy link
Contributor

coderabbitai bot commented Jan 3, 2025

Walkthrough

The pull request introduces significant changes to canvas and image decoding functionality across multiple files. The primary modifications focus on enhancing the canvas-decoder.ts file with a new recastBufferToMonoChannel function that converts image data to a single channel. The changes improve canvas handling by conditionally creating offscreen canvases and provide more flexible image processing capabilities. The modifications extend to disk-overlay-decoder.ts and its corresponding test file, updating function signatures and import statements to support the new image processing approach.

Changes

File Change Summary
app/packages/looker/src/worker/canvas-decoder.ts - Added recastBufferToMonoChannel function for single-channel image conversion
- Updated decodeWithCanvas to accept cls parameter
- Improved offscreen canvas creation logic
app/packages/looker/src/worker/disk-overlay-decoder.ts - Added HEATMAP and SEGMENTATION imports
- Modified decodeWithCanvas call to include class parameter
app/packages/looker/src/worker/disk-overlay-decoder.test.ts - Updated test cases for decodeWithCanvas
- Added test suite for recastBufferToMonoChannel

Possibly related PRs

Suggested labels

bug, app

Suggested reviewers

  • benjaminpkane
  • ritch

Poem

🐰 In bytes of canvas, magic unfurls
A rabbit's dance of pixels and swirls
One channel to rule them all
From RGBA's colorful sprawl
Decoding images with techno-art pearls! 🎨


📜 Recent review details

Configuration used: .coderabbit.yaml
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between b9bea14 and c68f7f3.

📒 Files selected for processing (3)
  • app/packages/looker/src/worker/canvas-decoder.ts (4 hunks)
  • app/packages/looker/src/worker/disk-overlay-decoder.test.ts (5 hunks)
  • app/packages/looker/src/worker/disk-overlay-decoder.ts (2 hunks)
👮 Files not reviewed due to content moderation or server errors (3)
  • app/packages/looker/src/worker/canvas-decoder.ts
  • app/packages/looker/src/worker/disk-overlay-decoder.ts
  • app/packages/looker/src/worker/disk-overlay-decoder.test.ts
🧰 Additional context used
📓 Path-based instructions (3)
app/packages/looker/src/worker/disk-overlay-decoder.test.ts (1)

Pattern **/*.{ts,tsx}: Review the Typescript and React code for conformity with best practices in React, Recoil, Graphql, and Typescript. Highlight any deviations.

app/packages/looker/src/worker/disk-overlay-decoder.ts (1)

Pattern **/*.{ts,tsx}: Review the Typescript and React code for conformity with best practices in React, Recoil, Graphql, and Typescript. Highlight any deviations.

app/packages/looker/src/worker/canvas-decoder.ts (1)

Pattern **/*.{ts,tsx}: Review the Typescript and React code for conformity with best practices in React, Recoil, Graphql, and Typescript. Highlight any deviations.

⏰ Context from checks skipped due to timeout of 90000ms (5)
  • GitHub Check: test / test-python (ubuntu-latest-m, 3.10)
  • GitHub Check: test / test-app
  • GitHub Check: build / build
  • GitHub Check: e2e / test-e2e
  • GitHub Check: lint / eslint

Thank you for using CodeRabbit. We offer it for free to the OSS community and would appreciate your support in helping us grow. If you find it useful, would you consider giving us a shout-out on your favorite social media?

❤️ Share
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Generate unit testing code for this file.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai generate unit testing code for this file.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and generate unit testing code.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai generate docstrings to generate docstrings for this PR. (Beta)
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 0

🧹 Nitpick comments (2)
app/packages/looker/src/worker/canvas-decoder.ts (2)

44-50: Clarify the documentation for in-place modification.
The JSDoc mentions “sets the buffer in place,” but the function returns a new sliced buffer. Consider clarifying this detail to avoid confusion.


Line range hint 70-121: Functionality looks good; consider a fallback for non-OffscreenCanvas contexts.
The code properly handles grayscale and heatmap cases. You may also consider a fallback path if OffscreenCanvas isn’t supported or the usage environment is unknown.

📜 Review details

Configuration used: .coderabbit.yaml
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 3fbee6c and b9bea14.

📒 Files selected for processing (3)
  • app/packages/looker/src/worker/canvas-decoder.ts (4 hunks)
  • app/packages/looker/src/worker/disk-overlay-decoder.test.ts (5 hunks)
  • app/packages/looker/src/worker/disk-overlay-decoder.ts (2 hunks)
🧰 Additional context used
📓 Path-based instructions (3)
app/packages/looker/src/worker/disk-overlay-decoder.test.ts (1)

Pattern **/*.{ts,tsx}: Review the Typescript and React code for conformity with best practices in React, Recoil, Graphql, and Typescript. Highlight any deviations.

app/packages/looker/src/worker/disk-overlay-decoder.ts (1)

Pattern **/*.{ts,tsx}: Review the Typescript and React code for conformity with best practices in React, Recoil, Graphql, and Typescript. Highlight any deviations.

app/packages/looker/src/worker/canvas-decoder.ts (1)

Pattern **/*.{ts,tsx}: Review the Typescript and React code for conformity with best practices in React, Recoil, Graphql, and Typescript. Highlight any deviations.

🔇 Additional comments (12)
app/packages/looker/src/worker/canvas-decoder.ts (3)

1-1: No issues with the new import statement.
Looks good to import the necessary constant here.


4-13: Ensure proper fallback or validation for OffscreenCanvas availability.
If OffscreenCanvas is unavailable in the environment, canvasAndCtx will remain undefined, but usage later forces a non-null assertion. This can lead to runtime errors in older or unsupported browsers.


51-68: Verify stride assumptions to prevent out-of-bounds reads.
If stride * totalPixels exceeds the buffer length, the loop could read beyond the array. Confirm all usage ensures safe bounds.

✅ Verification successful

Let me gather more information about the test cases and usage.


Let me check the actual usage in canvas-decoder.ts to see how stride is controlled.


Stride usage is safe and well-controlled

The verification shows that recastBufferToMonoChannel is used safely:

  1. The function is only called in two controlled scenarios in decodeWithCanvas:

    • When channels === 1 (grayscale PNG), with a fixed stride of 4 for RGBA data
    • When cls === HEATMAP && channels > 1, with the actual channel count as stride
  2. The test cases confirm safe usage with various strides (1, 3, 4) and validate correct output

  3. The input buffer is always from ImageData.data which is guaranteed to be properly sized for the image dimensions, ensuring stride * totalPixels never exceeds the buffer length

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Searches for all calls to recastBufferToMonoChannel to see if stride is always controlled
rg -A 3 "recastBufferToMonoChannel"

Length of output: 3594


Script:

#!/bin/bash
# Get the test cases to understand how stride is used
cat app/packages/looker/src/worker/disk-overlay-decoder.test.ts

Length of output: 8739


Script:

#!/bin/bash
# Get the full canvas-decoder.ts file to see how stride is used
cat app/packages/looker/src/worker/canvas-decoder.ts

Length of output: 3895

app/packages/looker/src/worker/disk-overlay-decoder.ts (3)

2-7: Imports look appropriate for label class constants.
These added imports are consistent with usage in the file.


11-11: Importing recastBufferToMonoChannel is acceptable.
The new import aligns with the added decoding logic in canvas-decoder.


122-122: Updated decodeWithCanvas call is correct.
Passing cls to decodeWithCanvas aligns with the function’s updated signature.

app/packages/looker/src/worker/disk-overlay-decoder.test.ts (6)

2-2: Added imports match new overlay classes.
Bringing in DETECTIONS, HEATMAP, and SEGMENTATION is consistent with the tested logic.


7-7: Imports decodeWithCanvas and recastBufferToMonoChannel for testing.
Including the new function for deeper test coverage is a good practice.


19-28: Mocking approach looks reasonable.
Using vi.importActual ensures the main logic remains intact while selectively mocking decodeWithCanvas.


95-95: Ensures decodeWithCanvas is invoked with SEGMENTATION.
Confirming the correct class parameter in the test is appropriate.


131-131: Ensures decodeWithCanvas is invoked with HEATMAP.
Validates that the heatmap label type is handled properly.


213-286: Comprehensive tests for recastBufferToMonoChannel.
These tests cover various strides and buffer shapes, making the solution robust.

Copy link
Contributor

@benjaminpkane benjaminpkane left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

LGTM

@benjaminpkane benjaminpkane merged commit 496e962 into develop Jan 7, 2025
12 checks passed
@benjaminpkane benjaminpkane deleted the optimization/heatmap branch January 7, 2025 17:16
ritch pushed a commit that referenced this pull request Jan 13, 2025
This was referenced Jan 20, 2025
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants