Repository navigation
Conversation
|
Some changes occurred in float parsing cc @tgross35 |
|
Thanks for the pull request, and welcome! The Rust Project has assigned @aapoalas (or someone else) to review your changes, you should hear from them (or someone else) within the next two weeks. Please see the contribution instructions and our LLM policy for more information. Why was this reviewer chosen?The reviewer was selected based on:
|
This comment has been minimized.
This comment has been minimized.
|
Can you please make the title and commit message summary something meaningful? We shouldn't have to cross reference issues to know what this is doing when seen in a list. |
|
To get a quick idea of perf changes, though I expect this should be a wash on 64-bit @bors try @rust-timer queue |
This comment has been minimized.
This comment has been minimized.
This comment has been minimized.
This comment has been minimized.
The first issue was ignoring later exponent digits even when the resulting correct parse value could still depend on them. The second issue was doing a subtraction in i32's that could overflow; now the subtraction is done in i64's and is then safely clamped. I have also added comments for "non-issues"; theoretical bugs that would only be reachable on exabyte-scale inputs.
14a8d75 to
1732f6e
Compare
This comment has been minimized.
This comment has been minimized.
|
Finished benchmarking commit (efd703d): comparison URL. Overall result: ❌✅ regressions and improvements - please read:Benchmarking means the PR may be perf-sensitive. Consider adding rollup=never if this change is not fit for rolling up. Next, please: If you can, justify the regressions found in this try perf run in writing along with @bors rollup=iffy rustc-perf Instruction countOur most reliable metric. Used to determine the overall result above. However, even this metric can be noisy.
Max RSS (memory usage)Results (primary 2.1%, secondary 4.8%)A less reliable metric. May be of interest, but not used to determine the overall result above.
CyclesResults (primary 2.2%, secondary -0.2%)A less reliable metric. May be of interest, but not used to determine the overall result above.
Binary sizeThis perf run didn't have relevant results for this metric. Bootstrap: 494.567s -> 490.54s (-0.81%) |
|
r? @tgross35 |
|
|
There was a problem hiding this comment.
Could you run the benchmarks at library/coretests/benches/num/{flt2dec,dec2flt} before and after this PR and post the outputs? I'm thinking this may come with a small regression, which is why I'm wondering if it may be better to error on excessively long inputs.
There was a problem hiding this comment.
Can you cover f16 in these tests too? With the target_has_reliable_f16 gate like other existing tests.
There was a problem hiding this comment.
yes will do. it was excluded just because of the examples rounded to zero in f16. But I think examples may exist that work across types.
| assert_eq!(long.parse::<f64>().map(f64::to_bits), Ok(0x3d719799812dea11)); | ||
| assert_eq!(long.parse::<f32>(), short.parse::<f32>()); | ||
|
|
||
| #[cfg(any(target_pointer_width = "32", target_pointer_width = "64"))] |
There was a problem hiding this comment.
Could you note why 16-bit is excluded?
| let long = format!("{short}{}", "0".repeat(100_000)); | ||
| assert_eq!(short.parse::<f64>().map(f64::to_bits), Ok(0x3d719799812dea11)); | ||
| assert_eq!(long.parse::<f64>().map(f64::to_bits), Ok(0x3d719799812dea11)); | ||
| assert_eq!(long.parse::<f32>(), short.parse::<f32>()); |
There was a problem hiding this comment.
This test fails when current std is built with overflow checks, right? It passes on the playground.
Any idea if it's possible to write a test that fails without overflow checks enabled due to bad wrapping behavior?
There was a problem hiding this comment.
As far as I know, the previous overflows always worked out to round the right way so that overflow-panic was the only problem; you couldn't show it with actual values.
| if matches!(s.first(), Some(&x) if x.is_ascii_digit()) { | ||
| *s_ref = s.parse_digits(|digit| { | ||
| // no overflows here, saturate well before overflow | ||
| if exponent < 0x10000 { | ||
| // The exponent is at most 10 * 2^59 - 1, which is small enough for i64. | ||
| // We stop accumulating the exponent once it's larger than 2^59 - 1, knowing that | ||
| // a fractional part small enough for an even larger exponent to matter requires | ||
| // exabyte-scale input size. | ||
| if exponent < (1_i64 << 59) { | ||
| exponent = 10 * exponent + digit as i64; | ||
| } | ||
| }); | ||
| if negative { Some(-exponent) } else { Some(exponent) } | ||
| } else { | ||
| *s_ref = s; | ||
| None | ||
| } |
There was a problem hiding this comment.
Compared to the current version, this adds a check for s.first(). Does that matter?
There was a problem hiding this comment.
Hm, I think this may actually be possible to simplify to:
let mut parsed_any = false;
*s_ref = s.parse_digits(|digit| {
parsed_any = true;
// rest of this block that currently exists
});
if parsed_any {
if negative { Some(-exponent) } else { Some(exponent) }
} else {
None
}since parse_digits does the check right?
| // no overflows here, saturate well before overflow | ||
| if exponent < 0x10000 { | ||
| // The exponent is at most 10 * 2^59 - 1, which is small enough for i64. | ||
| // We stop accumulating the exponent once it's larger than 2^59 - 1, knowing that | ||
| // a fractional part small enough for an even larger exponent to matter requires | ||
| // exabyte-scale input size. | ||
| if exponent < (1_i64 << 59) { | ||
| exponent = 10 * exponent + digit as i64; | ||
| } |
There was a problem hiding this comment.
Should we just return an error on massive inputs, like 1 << 40, rather than trying to parse? We'd have to ask libs for input, but if this makes it easier to reason about overflow then I imagine it could be worth it. Nobody sane is using a full terabyte to encode a single float.
| } | ||
| s = s.parse_digits(|digit| d.try_add_digit(digit)); | ||
| d.decimal_point = s.len() as i32 - first.len() as i32; | ||
| fractional_count = first.len() - s.len(); |
There was a problem hiding this comment.
I think the name parsed_fractional_digits may be more clear
| let significant_count = d.num_digits; | ||
| if d.num_digits != 0 { | ||
| // Ignore the trailing zeros if there are any | ||
| let mut n_trailing_zeros = 0; | ||
| for &c in start[..(start.len() - s.len())].iter().rev() { | ||
| if c == b'0' { | ||
| n_trailing_zeros += 1; | ||
| } else if c != b'.' { | ||
| break; | ||
| } | ||
| } | ||
| d.decimal_point += n_trailing_zeros as i32; | ||
| d.num_digits -= n_trailing_zeros; | ||
| d.decimal_point += d.num_digits as i32; | ||
| if d.num_digits > DecimalSeq::MAX_DIGITS { | ||
| d.truncated = true; | ||
| d.num_digits = DecimalSeq::MAX_DIGITS; | ||
| } | ||
| } |
There was a problem hiding this comment.
significant_count doesn't seem to be the actual count of significant digits, since trailing zeros are still counted.
| }); | ||
|
|
||
| d.decimal_point += if neg_exp { -exp_num } else { exp_num }; | ||
| explicit = parse_scientific(&mut s).unwrap_or(0); |
| s = s.parse_digits(|digit| d.try_add_digit(digit)); | ||
| d.decimal_point = s.len() as i32 - first.len() as i32; | ||
| fractional_count = first.len() - s.len(); | ||
| } | ||
|
|
||
| let significant_count = d.num_digits; | ||
| if d.num_digits != 0 { | ||
| // Ignore the trailing zeros if there are any | ||
| let mut n_trailing_zeros = 0; | ||
| for &c in start[..(start.len() - s.len())].iter().rev() { | ||
| if c == b'0' { | ||
| n_trailing_zeros += 1; | ||
| } else if c != b'.' { | ||
| break; | ||
| } | ||
| } | ||
| d.decimal_point += n_trailing_zeros as i32; | ||
| d.num_digits -= n_trailing_zeros; | ||
| d.decimal_point += d.num_digits as i32; | ||
| if d.num_digits > DecimalSeq::MAX_DIGITS { | ||
| d.truncated = true; | ||
| d.num_digits = DecimalSeq::MAX_DIGITS; | ||
| } | ||
| } | ||
|
|
||
| let mut explicit = 0; | ||
| if let Some((&ch, s_next)) = s.split_first() { | ||
| if ch == b'e' || ch == b'E' { | ||
| s = s_next; | ||
| let mut neg_exp = false; | ||
| if let Some((&ch, s_next)) = s.split_first() { | ||
| neg_exp = ch == b'-'; | ||
| if ch == b'-' || ch == b'+' { | ||
| s = s_next; | ||
| } | ||
| } | ||
| let mut exp_num = 0_i32; | ||
|
|
||
| s.parse_digits(|digit| { | ||
| if exp_num < 0x10000 { | ||
| exp_num = 10 * exp_num + digit as i32; | ||
| } | ||
| }); | ||
|
|
||
| d.decimal_point += if neg_exp { -exp_num } else { exp_num }; | ||
| explicit = parse_scientific(&mut s).unwrap_or(0); | ||
| } | ||
| } | ||
| d.decimal_point = final_decimal_point(significant_count, fractional_count, explicit); | ||
|
|
||
| for i in d.num_digits..DecimalSeq::MAX_DIGITS_WITHOUT_OVERFLOW { | ||
| d.digits[i] = 0; | ||
| } | ||
|
|
||
| d | ||
| } |
There was a problem hiding this comment.
Imho the existing version is a bit easier to follow. Could the same behavior be accomplished by replacing d.decimal_point with a decimal_point: i64 and doing the same math inline? Rather than stashing the values and computing with them in final_decimal_point. Then clamp right before assigning to d.decimal_point.
|
Reminder, once the PR becomes ready for a review, use |
|
I'm attaching benchmarks (attachment was LLM prepared). t-tests show the small improvement as statistically significant (.001) and the small regression not significant (.4). So I think on performance this seems ok? I think erroring on huge inputs would be reasonable; the current code is correct even for inputs up to 2^58. But there are inputs that make the previous code wrong even of size 65KiB or so, which I suspect is too small to want to refuse, even if clearly pathological. I will prepare a version incorporating your other suggestions; should I go ahead and include an error on huge inputs (and is there a preferred way for how/where to do that handling?) |
|
Interesting, that's a nice little win! Wonder where exactly it came from. If an error on huge inputs makes sense, could you do that in a separate PR? Then we can nominate it for discussion separately from the fix here since, with the limit in mind, it may be worth reworking the rest a bit. Please paste output in the message so we don't need to download anything, unless it's huge (then consider a gist). You can hide it in |
View all comments
Fixes #163674
Fixes #163676
The first issue was ignoring later exponent digits even when the resulting correct parse value could still depend on them.
The second issue was doing a subtraction in i32's that could overflow; now the subtraction is done in i64's and is then safely clamped.
I have also added comments for "non-issues"; theoretical bugs that would only be reachable on exabyte-scale inputs.
These issues (and non-issues) were discovered in an LLM-based autonomous Lean formalization project which formalized mathematical claims about the actual behavior of the dec2flt library. The code changes were written and initially reviewed by agents in that process; I have also carefully reviewed the changes and wrote the comments (and e.g., this message) myself.
@tgross35 offered to serve as a reviewer for these changes under the experimental LLM contribution policy.
r ? @tgross35