Skip to content

Implement uniform normal and integers distributions - #257

Open
vishakhaojha57 wants to merge 2 commits into
mohu-org:mainfrom
vishakhaojha57:issue-140-rng
Open

Implement uniform normal and integers distributions#257
vishakhaojha57 wants to merge 2 commits into
mohu-org:mainfrom
vishakhaojha57:issue-140-rng

Conversation

@vishakhaojha57

@vishakhaojha57 vishakhaojha57 commented May 30, 2026

Copy link
Copy Markdown

What

Why

How

Checklist

  • cargo test --workspace passes
  • cargo clippy --workspace -- -D warnings passes
  • cargo fmt --all applied
  • CHANGELOG.md updated (if user-facing change)
  • Benchmarks added or updated (if performance-sensitive path)

Summary by CodeRabbit

  • New Features
    • Generate random tensors with a uniform distribution by specifying lower and upper bounds.
    • Generate random tensors with a normal distribution by specifying mean and standard deviation.
    • Generate random integer tensors with configurable bounds.
    • All generators accept custom tensor shapes and validate input parameters.

@coderabbitai

coderabbitai Bot commented May 30, 2026

Copy link
Copy Markdown

Review Change Stack

Warning

Review limit reached

@vishakhaojha57, we couldn't start this review because you've reached your PR review rate limit.

More reviews will be available in 20 minutes and 9 seconds. Learn how PR review limits work.

Your organization has run out of usage credits. Purchase more in the billing tab.

⌛ How to resolve this issue?

After more reviews become available, a review can be triggered using the @coderabbitai review command as a PR comment. Alternatively, push new commits to this PR.

We recommend that you space out your commits to avoid hitting the rate limit.

🚦 How do rate limits work?

CodeRabbit enforces hourly rate limits for each developer per organization.

Our paid plans include higher PR review limits than trial, open-source, and free plans. In all cases, reviews become available again over time. During sustained high-volume PR review activity, CodeRabbit may temporarily slow when the next review becomes available.

Please see our Fair Usage Limits Policy for further information.

ℹ️ Review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro Plus

Run ID: 548ad02e-2242-44ac-85c9-d7ea4f0bcf29

📥 Commits

Reviewing files that changed from the base of the PR and between 5c6a164 and 36b223f.

📒 Files selected for processing (2)
  • crates/mohu-random/src/continuous.rs
  • crates/mohu-random/src/discrete.rs
📝 Walkthrough

Walkthrough

Adds three public random tensor generators in mohu-random: uniform(shape, low, high), normal(shape, mean, std), and integers(shape, low, high). Each validates bounds, generates flat samples via the rand RNG, constructs a Buffer from samples, and reshapes it to the requested shape.

Changes

Random Tensor Sampling

Layer / File(s) Summary
Continuous distributions (uniform and normal)
crates/mohu-random/src/continuous.rs
Adds pub fn uniform(shape: &[usize], low: f64, high: f64) -> MohuResult<Buffer> (validates finite bounds and high>low; samples n f64 uniformly) and pub fn normal(shape: &[usize], mean: f64, std: f64) -> MohuResult<Buffer> (validates finite positive std; samples n f64 via Box–Muller-style transform avoiding u1==0). Both build a Buffer from flat samples and reshape to shape.
Discrete integers distribution
crates/mohu-random/src/discrete.rs
Adds pub fn integers(shape: &[usize], low: i64, high: i64) -> MohuResult<Buffer> which validates high>low, samples n i64 values with rng.random_range(low..high), constructs a Buffer and reshapes to shape.

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~20 minutes

Possibly related issues

Poem

🐰 I hopped through numbers, smooth and bold,
Uniform fields and bells of gold,
Integers clatter, normals sing,
I stitch them into one soft string,
Shape by shape, the random grows—hooray! 🎲

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 0.00% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title clearly summarizes the main changes: adding three distribution functions (uniform, normal, and integers) to the random number generation module.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands and usage tips.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Actionable comments posted: 4

🧹 Nitpick comments (1)
crates/mohu-random/src/continuous.rs (1)

23-24: ⚡ Quick win

Add error context to propagated ?.

Buffer::from_vec and reshape errors propagate without describing what was attempted. Per convention, attach context (e.g. .with_context(|| ...)). Same pattern applies to normal (Lines 51-52) and integers in discrete.rs.

♻️ Example
-    let buf = Buffer::from_vec(data)?;
-    buf.reshape(shape)
+    let buf = Buffer::from_vec(data).context("building uniform sample buffer")?;
+    buf.reshape(shape).context("reshaping uniform samples to target shape")

As per coding guidelines: "Wrap error context with .context(...) or .with_context(|| ...)".

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@crates/mohu-random/src/continuous.rs` around lines 23 - 24, The
Buffer::from_vec(...) and buf.reshape(...) calls currently propagate errors with
? and need contextualized errors; update the code in continuous.rs to call
Buffer::from_vec(data).with_context(|| "creating Buffer from data for
<function/context name>")? and then buf.reshape(shape).with_context(||
format!("reshaping Buffer to {:?} in <function/context name>", shape))? (replace
<function/context name> with the containing function like `sample` or the public
API name), and apply the same pattern to the `normal` implementation (the two
calls around lines 51-52) and to `integers` in discrete.rs—use .context(...) or
.with_context(|| ...) on each fallible call so logs show what operation failed
and include identifying info (function name and parameters) in the message.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@crates/mohu-random/src/continuous.rs`:
- Around line 7-13: The uniform function currently only checks high <= low,
which misses NaN/inf cases; update Mohu-random's uniform(shape: &[usize], low:
f64, high: f64) to also validate that both low.is_finite() and high.is_finite()
are true (and still enforce high > low), returning MohuError::domain("uniform",
"...") with an appropriate message when they are not finite or when high <= low,
before calling random_range(low..high).
- Around line 40-47: The Box–Muller implementation can produce inf/NaN when u1
== 0.0; change how u1 is drawn so it lies in (0,1] instead of [0,1). Replace the
current `let u1: f64 = rng.random();` with a non-zero mapping such as `let u1:
f64 = 1.0 - rng.random();` (or loop/retry if zero) so `u1.ln()` is safe; keep
the rest of the `z0` computation and returned expression (`z0`, `u2`, `mean +
std * z0`) unchanged.
- Around line 8-13: Replace the manual bound-check returns with the ensure!
macro: for continuous::uniform, swap the if high <= low { return
Err(MohuError::domain("uniform", "high must be greater than low")); } with
ensure!(high > low, MohuError::domain("uniform", "high must be greater than
low")); likewise update the similar validation in continuous::normal and
discrete::integers to use ensure!(cond, MohuError::domain(...)) with the
identical domain strings and messages so the same error values are produced.

In `@crates/mohu-random/src/discrete.rs`:
- Around line 7-24: Replace the explicit return Err(...) check in integers with
the project's ensure! convention (ensure!(high > low,
MohuError::domain("integers", "high must be greater than low"))), and propagate
errors from Buffer::from_vec(data) and buf.reshape(shape) with contextual
messages instead of plain ?; i.e., call
Buffer::from_vec(data).context("integers: failed to create buffer from vec")?
and then buf.reshape(shape).context("integers: failed to reshape buffer")? so
both failure points include the "integers" context and follow the same
error-context conventions used in continuous.rs.

---

Nitpick comments:
In `@crates/mohu-random/src/continuous.rs`:
- Around line 23-24: The Buffer::from_vec(...) and buf.reshape(...) calls
currently propagate errors with ? and need contextualized errors; update the
code in continuous.rs to call Buffer::from_vec(data).with_context(|| "creating
Buffer from data for <function/context name>")? and then
buf.reshape(shape).with_context(|| format!("reshaping Buffer to {:?} in
<function/context name>", shape))? (replace <function/context name> with the
containing function like `sample` or the public API name), and apply the same
pattern to the `normal` implementation (the two calls around lines 51-52) and to
`integers` in discrete.rs—use .context(...) or .with_context(|| ...) on each
fallible call so logs show what operation failed and include identifying info
(function name and parameters) in the message.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro Plus

Run ID: bbaedce0-a012-40a0-bcc3-9b2d165bd9b5

📥 Commits

Reviewing files that changed from the base of the PR and between 1de1da3 and 1edfe76.

📒 Files selected for processing (2)
  • crates/mohu-random/src/continuous.rs
  • crates/mohu-random/src/discrete.rs

Comment thread crates/mohu-random/src/continuous.rs Outdated
Comment thread crates/mohu-random/src/continuous.rs Outdated
Comment thread crates/mohu-random/src/continuous.rs Outdated
Comment thread crates/mohu-random/src/discrete.rs Outdated
Comment on lines +7 to +24
pub fn integers(shape: &[usize], low: i64, high: i64) -> MohuResult<Buffer> {
if high <= low {
return Err(MohuError::domain(
"integers",
"high must be greater than low",
));
}

let n: usize = shape.iter().product();

let mut rng = rand::rng();

let data: Vec<i64> = (0..n)
.map(|_| rng.random_range(low..high))
.collect();

let buf = Buffer::from_vec(data)?;
buf.reshape(shape)

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion | 🟠 Major | ⚡ Quick win

Same ensure! and error-context conventions apply here.

The return Err(...) at Lines 8-13 should use ensure!, and the ? propagation at Lines 23-24 should add .context(...), as detailed in the continuous.rs comments. Logic (exclusive high, i64 range sampling) is otherwise correct.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@crates/mohu-random/src/discrete.rs` around lines 7 - 24, Replace the explicit
return Err(...) check in integers with the project's ensure! convention
(ensure!(high > low, MohuError::domain("integers", "high must be greater than
low"))), and propagate errors from Buffer::from_vec(data) and buf.reshape(shape)
with contextual messages instead of plain ?; i.e., call
Buffer::from_vec(data).context("integers: failed to create buffer from vec")?
and then buf.reshape(shape).context("integers: failed to reshape buffer")? so
both failure points include the "integers" context and follow the same
error-context conventions used in continuous.rs.

@codecov-commenter

Copy link
Copy Markdown

⚠️ Please install the 'codecov app svg image' to ensure uploads and comments are reliably processed by Codecov.

Codecov Report

❌ Patch coverage is 0% with 38 lines in your changes missing coverage. Please review.

Files with missing lines Patch % Lines
crates/mohu-random/src/continuous.rs 0.00% 29 Missing ⚠️
crates/mohu-random/src/discrete.rs 0.00% 9 Missing ⚠️

📢 Thoughts on this report? Let us know!

Signed-off-by: Vishakha Ojha <vishakhaojha57@gmail.com>
Signed-off-by: Vishakha Ojha <vishakhaojha57@gmail.com>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants