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

chore: upgrade ndarray #42

Merged
merged 3 commits into from
Nov 1, 2024
Merged

chore: upgrade ndarray #42

merged 3 commits into from
Nov 1, 2024

Conversation

hadronzoo
Copy link
Contributor

@hadronzoo hadronzoo commented Oct 31, 2024

Upgrade ndarray and transitive dependencies.

  • Updated dependency versions
  • Add clippy pedantic lint to Cargo.toml to align with CI check
  • Allow LAPACK pedantic clippy lints which are failing
  • Fix feature flag naming for consistency

Copy link

coderabbitai bot commented Oct 31, 2024

Walkthrough

The changes in this pull request involve updates to the Cargo.toml file for the petal-decomposition package, specifically modifying dependency versions for lair and ndarray. The lair dependency is updated from version 0.6 to 0.7, while ndarray is updated from 0.15.2 to 0.16.1. Additionally, the development dependency for ndarray is adjusted to version 0.16 with the feature ["approx"]. A new section for Clippy lints is added. In src/lib.rs, the feature flag for the netlib_src crate is renamed from netlib_static to netlib-static. The src/linalg/lapack.rs file sees the introduction of new unsafe functions in the Lapack trait, enhancing linear algebra operations with improved error handling and memory management.

Changes

File Change Summary
Cargo.toml Updated lair from 0.6 to 0.7, ndarray from 0.15.2 to 0.16.1, and dev-dependency ndarray to version 0.16 with feature ["approx"]. Added [lints.clippy] section with pedantic = "warn".
src/lib.rs Modified feature flag from netlib_static to netlib-static. No other changes made.
src/linalg/lapack.rs Introduced several unsafe functions in the Lapack trait for linear algebra operations, with error handling and dynamic workspace allocation.

Poem

🐇 In the garden of code, we hop and we play,
With versions updated, we brighten the day.
Lair and ndarray, now fresh and anew,
With features aligned, our work shines right through.
So here’s to the changes, both small and grand,
In the world of Rust, we take a proud stand! 🌼


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 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.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

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

codecov bot commented Oct 31, 2024

Codecov Report

All modified and coverable lines are covered by tests ✅

Project coverage is 75.30%. Comparing base (6904f0c) to head (24a8a03).

Additional details and impacted files
@@            Coverage Diff             @@
##             main      #42      +/-   ##
==========================================
- Coverage   78.18%   75.30%   -2.89%     
==========================================
  Files           4        4              
  Lines         486      486              
==========================================
- Hits          380      366      -14     
- Misses        106      120      +14     

☔ View full report in Codecov by Sentry.
📢 Have feedback on the report? Share it here.

Copy link

@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

🧹 Outside diff range and nitpick comments (6)
src/linalg/lapack.rs (6)

Line range hint 58-61: Consider Refactoring Duplicate Code in unsafe fn Implementations

The implementations of gelqf, gesdd, gesvd, heev, and unglq contain similar patterns for workspace querying and allocation, error checking, and function calls. Refactoring this repeated code into a helper function could improve maintainability and reduce code duplication.

Example of refactored code using a helper function:

unsafe fn workspace_query_and_call<F, G, T>(
    lapack_func: F,
    m: i32,
    n: i32,
    args: G,
) -> Result<T, i32>
where
    F: Fn(/* appropriate parameters */),
    G: /* appropriate trait bounds */,
    T: /* appropriate return type */,
{
    // Implement the common logic here
}

Then, update each unsafe fn to use this helper function.

Also applies to: 85-88, 112-115, 142-145, 169-172


Line range hint 198-204: Safety Concern: Use of vec_uninit May Lead to Undefined Behavior

The vec_uninit function creates a vector with uninitialized elements and sets its length without initializing its contents. This can lead to undefined behavior if any of the uninitialized elements are accessed before being properly initialized. Rust's safety guarantees are compromised when using uninitialized memory unsafely.

Consider using Vec::with_capacity(n) and pushing initialized values, or leveraging functions like vec![MaybeUninit::<T>::uninit(); n] along with proper initialization steps. Alternatively, for types that are Copy, you could use vec![T::zero(); n] if zero initialization is acceptable.

Apply this diff to address the issue:

-unsafe fn vec_uninit<T: Sized>(n: usize) -> Vec<T> {
-    let mut v = Vec::with_capacity(n);
-    v.set_len(n);
-    v
-}
+use std::mem::MaybeUninit;
+
+unsafe fn vec_uninit<T: Sized>(n: usize) -> Vec<T> {
+    let v = Vec::<MaybeUninit<T>>::with_capacity(n);
+    // Ensure to properly initialize elements before use
+    // Implement initialization logic here
+    // Then, transmute Vec<MaybeUninit<T>> to Vec<T> if safe
+    v
+}

Ensure that all elements are properly initialized before any use to maintain memory safety.


Line range hint 31-38: Error Handling: Check Conversion from Self to usize

The usage of to_usize().expect("valid integer") assumes that the conversion from Self (which could be a floating-point type like f32 or f64) to usize will always succeed. However, if work_size[0] contains a value that cannot be converted to usize, this will cause a panic at runtime.

Consider adding proper error handling for the conversion to prevent potential panics.

Apply this diff to handle the conversion safely:

-let lwork = work_size[0].to_usize().expect("valid integer");
+let lwork = match work_size[0].to_usize() {
+    Some(val) => val,
+    None => return Err(-1), // Return an appropriate error code
+};

1-5: Remove Unnecessary Clippy Allowances

The file includes #![allow(...)] for several Clippy lints (cast_sign_loss, cast_possible_truncation, cast_possible_wrap). If these casts are intentional and reviewed, consider adding explanations or targeting the allowances more narrowly to the specific code that requires them. Otherwise, remove them to ensure Clippy can catch potential issues.


Line range hint 7-10: Organize Imports Alphabetically and Group by Crate

For better readability and maintainability, consider organizing the import statements alphabetically and grouping them by crate origin.

Apply this diff to organize the imports:

 use lair::Scalar;
+use num_complex::{Complex32, Complex64};
 use num_traits::{ToPrimitive, Zero};
 use std::cmp;
+use std::mem::MaybeUninit;

Line range hint 222-227: Typographical Error in Comment

There is a minor typo in the comment for vec_uninit:

"The caller must ensure that the elements of the vector are not used before they are initialized."

Consider rephrasing for clarity:

"The caller must ensure that the elements of the vector are properly initialized before use."

Apply this diff:

-/// they are initialized.
+/// they are properly initialized before use.
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between c8d5014 and 24a8a03.

📒 Files selected for processing (2)
  • Cargo.toml (3 hunks)
  • src/linalg/lapack.rs (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • Cargo.toml
🔇 Additional comments (1)
src/linalg/lapack.rs (1)

Line range hint 89-89: Potential Inconsistency in ld_a Parameter Passing

In the second call to the LAPACK functions within heev, gelqf, and unglq, the ld_a parameter is sometimes changed from ld_a to n. This could be intentional, but it may lead to unexpected behavior if ld_a is not equal to n.

Please verify that the ld_a parameter should be n in the second call. If this is not intentional, consider using ld_a consistently.

Run the following script to search for ld_a usage:

Also applies to: 116-116, 146-146

✅ Verification successful

The previous pattern might have been too specific. Let's broaden our search to find the LAPACK function calls and analyze the parameter patterns, particularly focusing on the mentioned functions heev, gelqf, and unglq.


Parameter Change in heev is Intentional and Correct

The search results confirm that the change from ld_a to n in the second call to heev is intentional and correct. This is because:

  1. The first call is a workspace query (with -1 work size) where the original ld_a is used to check the input matrix dimensions
  2. The second call uses n as the leading dimension because LAPACK's heev overwrites the input matrix with eigenvectors (when jobz = 'V'), which requires a square matrix with leading dimension equal to the order of the matrix (n)

The same pattern is not present in gelqf and unglq where ld_a is consistently used, as these routines have different matrix layout requirements. The implementation is correct as is.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Verify consistency of `ld_a` parameter in LAPACK function calls.

# Search for lines where LAPACK functions are called and check `ld_a` usage.
rg -A 2 '\$[a-z]+\(.*,&mut a, (ld_a|n),' src/linalg/lapack.rs

Length of output: 63


Script:

#!/bin/bash
# Let's try a broader search pattern to find LAPACK function calls
rg -A 5 '\$[a-z]+\(' src/linalg/lapack.rs

# Also search specifically for heev, gelqf, and unglq functions
rg -A 10 '(heev|gelqf|unglq)' src/linalg/lapack.rs

Length of output: 7271

@hadronzoo
Copy link
Contributor Author

hadronzoo commented Oct 31, 2024

It appears that the codecov/project check is mistaking the lint attribute as code, so it's misinterpreting this addition as a reduction in coverage.

@msk msk self-assigned this Oct 31, 2024
@msk msk merged commit d2a9d58 into petabi:main Nov 1, 2024
16 of 17 checks passed
msk added a commit that referenced this pull request Nov 1, 2024
@hadronzoo hadronzoo deleted the update-ndarray branch November 1, 2024 18:11
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