Repository navigation
Make Field macro a volatile cast - #11255
Conversation
|
The graph above shows the normalized running time for this PR against trunk on macro benchmarks from Sandmark. The results show that there is neither a definitive slowdown nor a speedup overall; there's a max 4% swing in both directions. Given that this PR is necessary for correctness, I would consider that there is nothing to be done on the performance side. |
|
@dra27 ran opam health check on this PR as well as this patch applied to 4.14. For 5.0.0+trunk, there are no new breakages. Every package that builds on trunk builds with this PR. For 4.14, the only breakage is |
|
The Sandmark results are a bit weird, as we don't see how the change could possibly improve performance. (Using volatile is supposed to disable some compiler optimizations only.) This suggests that the changes we observe, at least on the "speed up" part of the graph, are mostly tooling-related noise (maybe the different code generation creates weird code-placement effects, or maybe it is actually faster in some case to force the compiler to recompute reads, etc.). Given that the "slow down" parts seem comparable in magnitude to the "speed up" part, it's hard to tell if the results are actually meaningful. Said otherwise: for a change that should not impact performance at all, maybe what we should expect to observe in practice, because life is complicated, is for speedup/slowdown results to fall along a gaussian distribution centered at 0. I wonder whether the results here fit this model. |
|
I analyzed the outliers. The observed results are reproducible and not an artifact of sandmark.
|
|
I would say that there are different sorts of noise. Some sources of noise generate variance from one run of the benchmark to the other (and the benchmark setup is trying to eliminate it), or from one machine to the next. But there are other sorts of noise that still qualify as noise, because they are small changes in result that do not come from a fundamental change in runtime behavior, but unpredictable complex systems placed between our source code and the behaviors we observe (for example, CPUs and their micro-architectural effects). That latter source of "noise" (which I called "tooling noise") is what seems to be going on here. In this noise category, the performance difference that we observe on one benchmark is a deterministic function of the benchmark, but the effect on a family of benchmarks (the function from a benchmark to the performance difference) could be random/arbitrary. Maybe we can model the impact of this change as a random speedup/slowdown for each benchmark, following a Gaussian centered at 0 -- many programs seeing their performance unchanged, and a small number of benchmarks seeing small speedups or slowdowns. (Or maybe there is a mix of "micro-architectural effects with winners and losers" and actual real slowdowns, caused by say a specific runtime function being pessimized; in that case the average speedup/slowdown would be tilted towards the "slowdown" part, but if such an effect exists it is not clear in the benchmark suite.) In summary: we observe speedups of 4% that have no clear reason (possibly: obscure microarchitectural effects), which suggests that we can discard all performance effects of up to 4% as just weird magic. Only much larger changes would be representative, and there are none in this benchmark suite. |
|
Thanks for the summary. In the past, we have had features that introduce swings of 2-4% in both directions. A good approximation of the overall change is the geometric mean of the normalised running times. For this PR, the geomean is |
|
A possible testable null-hypothesis is that the change is no more likely to decrease performance than to increase them. P(D = d) = (1/2)^N N!/((N-D)!D!With 50 samples, this hypothesis can be rejected with a p-value of 5% if we observe 31 samples with decreased performances. Since this is not the case, this null hypothesis is not observably wrong. For testing a gaussian hypothesis, I would need to know the variance. @kayceesrk , if you send me the raw data I can have a look. However, I am not sure that the extremal values observed in the benchmark are compatible with a gaussian hypothesis: with 50 samples, it is possible to reject a gaussian hypothesis with 5% p-value if the maximum is greater than 3.08 σ and that might be the case here. |
|
It's surprisingly hard to find clear explanation on this problem that looks common, important and affecting people who are not experts in benchmark design. (What's the expected distribution of the performance impact of microarchitectural effects these days?) All I could find was STABILIZER: statistically sound performance evaluation, Curtsinger and Berger, 2013, a paper on a complex system to dynamically randomize the (code, heap, stack) layout of running programs, performed using instrumentation at the LLVM level. (It looks like it would be quite some amount of work to reproduce it in the OCaml compiler, but we could actually try to enable this on the OCaml runtime code.) They report that, using their randomization tool, they observe that layout effects follow a Gaussian distribution ("very often"; they don't on two specific benchmarks). |
|
Maybe we could have this general discussion (on interpreting Sandmark results) separately from this PR. But, yes, differences in code placement can affect execution times by several percents. To evaluate the impact of optimizations, I prefer to count the number of instructions executed, there's less noise this way. |
xavierleroy
left a comment
There was a problem hiding this comment.
There's a few extra points in the code where you could avoid a (value *) cast by declaring some variables or struct fields volatile value *. On the one hand, I like it when there are fewer casts. On the other hand those volatile declarations add noise. I don't feel strongly either way.
|
Building upon @xavierleroy's comments, I refactored the PR further to remove almost all of the casts of The only two places where we explicitly cast
|
gasche
left a comment
There was a problem hiding this comment.
I like the new patchset, it's clean, and the rationale for the change has been discussed at length. We haven't been able to detect a performance regression in the benchmarks, as we expected.
(I wondered if it would make sense to introduce an alias for volatile value *, maybe lvalue :-' but this is no priority.)
|
I think that a Changes entry would make sense: this is a user-visible change, including compared to 4.x, and it would be useful to provide clear context for it and also to credit Guillaume's contribution. |
xavierleroy
left a comment
There was a problem hiding this comment.
Looks very good to me. Thanks!
|
I would like to have a look at this PR, it seems like I will have various comments. Can you please leave me the time to review it later? In the meanwhile, I have not seen much discussion about the proposal at #10992 (comment) which motivates this PR. Would some memory-model expert who feel involved with OCaml please tell us what they think about it? |
Sounds good. Thanks for having a look. I'll wait until the review is completed to write the Changes entry. |
|
We need to make progress towards the 5.0 release, so @gadmm please review ASAP or tell us you can't do it, but don't make us wait. |
|
I'll give it a try over the week-end. |
To be clearer, this PR does not close #10992 by itself.
I would like that
Does this PR include a review that there are no other macros similar to
With
This is a bigger change than I expected. First, I think that But I am also worried that changing the signature of This, together with the risks of users avoiding
I was wondering (here and for other multicore benchmarks that show similar fluctuations) if you have tried to vary the compiler and the compilation options. Some compilation options create a different code layout, which can sometimes be enough to convince whether the performance swing is relevant or not. (In terms of Florian's qualitative criterion, it gives you more independent data points.) Can you please point me at the specs of the machine?
Does opam health check catch new warnings, or does it only catch them in the cases where the warning is turned into an error? |
Sure. It would be a good chance to include the documentation for
No.
Good point. Thanks for clarifying. Ideally, it would have been better than volatile cast if we were able to write
Right. The runtime is built error: passing argument 1 of ‘foo’ discards ‘volatile’ qualifier from pointer target type [-Werror=discarded-qualifiers]shows up. Unless the C parts of the libraries are also built with If not, I wonder whether we can do something simple like: alias gcc="gcc -Werror"to get an assessment of the failing packages.
No. We don't currently perform benchmarking with changing compiler and compiler options regularly. We will see fluctuations by changing the compilation option. However, it is hard to translate the observed fluctuations into actionable information. That said, what has been useful is to use the sandmark results as a starting point to analyse the performance of outliers in detail as I have done in #11255 (comment). Firstly, in addition to looking at the running time, the change in the number of instructions executed is useful to look at. But this can also throw surprising results. For the program which runs fastest with this PR compared to trunk ( From my perspective, this PR is needed for correctness. Since the performance impact is not significant, I would consider the performance impact to be acceptable.
Are you thinking about something like |
From an API user's perspective, the big visible change is that This proposal does make the assumption that few third-party codes take pointers inside blocks Assuming third-party code should better not work with pointers inside blocks, there's no need for a typedef. I like the verbosity of |
|
Dune doesn't add However, we don't do this in OCaml's build system either - for a release tag / tarball we also compile C objects without I don't think there's a reliable way to turn on |
|
Thanks for the response @dra27. I was under the false assumption that the lack of new failures with this PR indicated that third-party code was not taking internal pointers to blocks and using them in interesting ways. Like @xavierleroy, it would be interesting to see whether this pattern does occur in the wild, and how many packages are broken due to this change. That said, I don't think that the result of such an analysis should block this PR. |
|
It would be nice to have a look if any other macro needs the volatile cast so they are all fixed at once ( Yes I am thinking about something like I agree that adding |
|
Am I reading correctly that every one agree that this PR is a good compromise and a step forward? If so, I would propose to first merge this PR, and then move to reviewing other macros in subsequent PRs or issues. |
44d7bd4 to
751f8a7
Compare
|
I agree this PR is in good shape. I just rebased to fix conflicts and added a Changes entry. Will run CI precheck next. |
751f8a7 to
8062217
Compare
|
CI precheck is positive. Let's merge! |
|
I'll wait for more CI to run on trunk, then pick to 5.0. |
|
Thanks for pushing the PR across the line @Octachron and @xavierleroy. |
`Field(v,i)` is now `volatile`-qualified, to better handle races with concurrent updates in C or in OCaml. (More complete discussion at #10992.) `&Field(v,i)` now has type `volatile value *`. Add `volatile` qualifiers to `caml_modify`, `caml_initialize`, and in internal parts of the runtime system. (cherry picked from commit 0e09dc4)
|
CI looks globally good, so here is the 5.0 cherry-pick: 7b76f07 |
|
I opened an issue with my comment left without reply at #11426. |
| #define Op_atomic_val(x) ((atomic_value *) (x)) | ||
| /* Fields are numbered from 0. */ | ||
| #define Field(x, i) (((value *)(x)) [i]) /* Also an l-value. */ | ||
| #define Field(x, i) (((volatile value *)(x)) [i]) /* Also an l-value. */ |
There was a problem hiding this comment.
Field(x, 0) and Op_val(x) previously had the exact same behavior, but Field is now a volatile cast whereas Op_val went unchanged in this PR.
Was this on purpose?
There was a problem hiding this comment.
I had missed it, but perhaps #11426 will take care of that.

The PR addresses the issue with C FFI and the OCaml memory model. For context see, #10992.
The first commit make
Fieldmacro a volatile cast, and the second commit introducesLoad_fieldmacro that is not an l-value and performs an acquire load of the given field.Goal
The comment at #10992 (comment) gives a detailed description of the aim of the PR. I shall try to summarize the issue and the aim of the PR.
The PR #10972 performs a compilation of the OCaml memory model to C11 (
caml_modify,caml_atomic_*, etc) and hardware models (x86 and ARMv8). This compilation covers all of the FFI functions exceptField, which is the focus on #10992.Fieldmacro on trunk performs non-atomic reads. Since this is C, data races using theFieldmacro will have catch fire semantics.Can we make
Fieldmacro an_Atomiccast to avoid catch-fire semantics? No.Fieldmacro is also an l-value and makingFieldand_Atomiccast will make it not be an l-value. Our previous experience with the concurrent major GC shows that makingFieldnot an l-value breaks an awful lot of packages. Hence, we makeFielda volatile cast, which, in practice, avoids catch-fire semantics. See Linux kernel memory model https://www.open-std.org/jtc1/sc22/wg21/docs/papers/2020/p0124r7.html#Variable%20Access.We also introduce
Load_fieldmacro which does an acquire load. The aim of theLoad_fieldmacro is to provide a mechanism for users to read fields in C11 compatible fashion (and not "in practice" assumptions that comes withvolatilefields) that also preserves the ordering necessary for OCaml memory model. We shall encourage our users to start usingLoad_fieldin places whereFieldis used as an r-value. Technically,Load_fieldis only necessary for mutable fields, and immutable fields can be accessed usingFieldmacro. However, for users, it will be easier to switch toLoad_fieldunconditionally.Possible backwards compatibility concern
Given that
Fieldhas been made volatile, the uses of&Field(..)will have the typevolatile value *. This will cause C compiler to raise a warning about discarded quantifiers when functions that take avalue *argument are passedvolatile value *value.The PR includes changes to the types of certain functions (
caml_modify,caml_initialize, ...) to make the C compiler happy.Todo
&Field(..)using opam health check.CC @gadmm @stedolan.