Forwarded from Блог*
#prog #math #article
Написано на удивление доходчиво.
High Performance Correctly Rounded Math Libraries for 32-bit Floating Point Representations
Everyone uses math libraries (i.e., libm), which provide approximations for elementary functions. Surprisingly (or not), mainstream math libraries (i.e., Intel’s and GCC’s libm) do not produce correct results for several thousands of inputs! Developers of modern software systems are seldom aware of them, which affects the reproducibility and portability of software systems. This blog post describes our new method for synthesizing elementary functions that produces correct results for all inputs but is also significantly faster than the state of the art libraries, which have been optimized for decades.
<...>
The overall goal of our RLIBM project is to make correctly rounded elementary functions mandatory rather than a recommendation by the standards (at least for 32 bits or lower). In our RLIBM project, we have been making a case for generating polynomials that approximate the correctly rounded result of f(x) rather than the real value of f(x) because our goal is to generate correct, yet efficient implementations. By approximating the correctly rounded result, we consider both approximation errors (i.e., polynomial approximation) and rounding errors (i.e., with polynomial evaluation with finite precision representations), which enables the generation of correct results. One can use existing high-precision libraries, which are slow, to generate oracle correctly rounded results. Now our goal is to generate efficient polynomials that produce these correctly rounded results for all inputs. Given a correctly rounded result, there is an interval of real values around the correct result that the polynomial can produce, which still rounds to the correct result. This interval is the amount of freedom available that our polynomial generator has for a given input. Using this interval, our idea is to structure the problem of polynomial generation that produces correct results for all inputs as a linear programming (LP) problem. To scale to representations with a large number of inputs, we propose counterexample guided polynomial generation, generate piecewise polynomials rather than a single polynomial, and develop techniques that support various complex range reductions.
Написано на удивление доходчиво.
High Performance Correctly Rounded Math Libraries for 32-bit Floating Point Representations
Everyone uses math libraries (i.e., libm), which provide approximations for elementary functions. Surprisingly (or not), mainstream math libraries (i.e., Intel’s and GCC’s libm) do not produce correct results for several thousands of inputs! Developers of modern software systems are seldom aware of them, which affects the reproducibility and portability of software systems. This blog post describes our new method for synthesizing elementary functions that produces correct results for all inputs but is also significantly faster than the state of the art libraries, which have been optimized for decades.
<...>
The overall goal of our RLIBM project is to make correctly rounded elementary functions mandatory rather than a recommendation by the standards (at least for 32 bits or lower). In our RLIBM project, we have been making a case for generating polynomials that approximate the correctly rounded result of f(x) rather than the real value of f(x) because our goal is to generate correct, yet efficient implementations. By approximating the correctly rounded result, we consider both approximation errors (i.e., polynomial approximation) and rounding errors (i.e., with polynomial evaluation with finite precision representations), which enables the generation of correct results. One can use existing high-precision libraries, which are slow, to generate oracle correctly rounded results. Now our goal is to generate efficient polynomials that produce these correctly rounded results for all inputs. Given a correctly rounded result, there is an interval of real values around the correct result that the polynomial can produce, which still rounds to the correct result. This interval is the amount of freedom available that our polynomial generator has for a given input. Using this interval, our idea is to structure the problem of polynomial generation that produces correct results for all inputs as a linear programming (LP) problem. To scale to representations with a large number of inputs, we propose counterexample guided polynomial generation, generate piecewise polynomials rather than a single polynomial, and develop techniques that support various complex range reductions.
SIGPLAN Blog
High Performance Correctly Rounded Math Libraries for 32-bit Floating Point Representations
Everyone uses math libraries. Surprisingly, mainstream math libraries do not produce correct results for several thousands of inputs. Developers are seldom aware of them, which affects reproducibil…
Forwarded from Блог*
#prog #rust #article
Набор из трёх статей Niko Matsakis про дизайн параллельных итераторов в rayon. Впрочем, первая статья посвящена обзору обычных, последовательных итераторов. Если у вас есть опыт работы с Rust — первую статью можно спокойно не читать.
Parallel Iterators Part 1: Foundations
Parallel Iterators Part 2: Producers
Parallel iterators, part 3: Consumers
И ещё небольшой документ в репе rayon о том, как реализовывать параллельные итераторы.
Набор из трёх статей Niko Matsakis про дизайн параллельных итераторов в rayon. Впрочем, первая статья посвящена обзору обычных, последовательных итераторов. Если у вас есть опыт работы с Rust — первую статью можно спокойно не читать.
Parallel Iterators Part 1: Foundations
Parallel Iterators Part 2: Producers
Parallel iterators, part 3: Consumers
И ещё небольшой документ в репе rayon о том, как реализовывать параллельные итераторы.
docs.rs
rayon - Rust
Rayon is a data-parallelism library that makes it easy to convert sequential computations into parallel.
Forwarded from Блог*
#prog #performancetrap #video
"Performance Matters" by Emery Berger
Фактически презентация двух инструментов для анализа производительности.
Первый — Stabilizer. Производительность программ в немалой степени зависит от того, как данные располагаются в памяти, и от окружения, в котором программы запускаются. Автор видео ссылается на статью, которая показывает, что эффект этих переменных может быть весьма значителен и перекрывать даже разницу между оптимизированным и неоптимизированным кодом. Stabilizer в рантайме каждые пол-секунды меняет раскладку кода и данных в куче, что позволяет снимать профиль производительности с учётом всех возможных влияний раскладки кода. Из-за применимости в данном случае центральной предельной теоремы общее влияние раскладки описывается (для достаточно большого количества исследованных данных) нормальным распределением, что позволяет задействовать статистические методы для того, чтобы замерить, насколько вклад в изменение производительности обусловлен изменениями в коде. К сожалению, этот инструмент более активно не развивается.
Второй инструмент (более живой) — это coz, causal profiler. Этот профайлер позволяет ценой небольших аннотаций исходного кода оценить, насколько сильно изменение производительности одного компонента сказывается на производительности системы в целом. Так как просто взять и ускорить код невозможно, coz достигает требуемых эффектов за счёт замедления всех остальных компонентов. В видео рассказывается о том, как coz помог в реальных случаях, на какие неожиданные узкие места указывал и о том, насколько хорошо замеренные прибавки в производительности согласовывались с предсказаниями инструмента.
Забавно, что это видео я уже смотрел, Даня упоминал coz у себя на канале, но только сейчас наткнулся на него снова и выложил у себя.
"Performance Matters" by Emery Berger
Фактически презентация двух инструментов для анализа производительности.
Первый — Stabilizer. Производительность программ в немалой степени зависит от того, как данные располагаются в памяти, и от окружения, в котором программы запускаются. Автор видео ссылается на статью, которая показывает, что эффект этих переменных может быть весьма значителен и перекрывать даже разницу между оптимизированным и неоптимизированным кодом. Stabilizer в рантайме каждые пол-секунды меняет раскладку кода и данных в куче, что позволяет снимать профиль производительности с учётом всех возможных влияний раскладки кода. Из-за применимости в данном случае центральной предельной теоремы общее влияние раскладки описывается (для достаточно большого количества исследованных данных) нормальным распределением, что позволяет задействовать статистические методы для того, чтобы замерить, насколько вклад в изменение производительности обусловлен изменениями в коде. К сожалению, этот инструмент более активно не развивается.
Второй инструмент (более живой) — это coz, causal profiler. Этот профайлер позволяет ценой небольших аннотаций исходного кода оценить, насколько сильно изменение производительности одного компонента сказывается на производительности системы в целом. Так как просто взять и ускорить код невозможно, coz достигает требуемых эффектов за счёт замедления всех остальных компонентов. В видео рассказывается о том, как coz помог в реальных случаях, на какие неожиданные узкие места указывал и о том, насколько хорошо замеренные прибавки в производительности согласовывались с предсказаниями инструмента.
Забавно, что это видео я уже смотрел, Даня упоминал coz у себя на канале, но только сейчас наткнулся на него снова и выложил у себя.
YouTube
"Performance Matters" by Emery Berger
Performance clearly matters to users. For example, the most common software update on the AppStore is "Bug fixes and performance enhancements." Now that Moore's Law has ended, programmers have to work hard to get high performance for their applications. But…
Forwarded from Блог*
#prog #rust #article
The registers of Rust
Лодочник рассматривает существующие эффекты в Rust (асинхронность, итерирование, ошибочность) с точки зрения регистров (не процессорных, а в том смысле, в котором это слово используется в социолингвистике) и довольно аргументированно доказывает, что усилия по развитию асинхронности в Rust идут в не совсем нужном направлении. Даже если вы с ним не согласны, предложенный им способ рассмотрения фич языка программирования довольно полезен.
И продолжения:
Patterns & Abstractions
Const as an auto trait
The registers of Rust
Лодочник рассматривает существующие эффекты в Rust (асинхронность, итерирование, ошибочность) с точки зрения регистров (не процессорных, а в том смысле, в котором это слово используется в социолингвистике) и довольно аргументированно доказывает, что усилия по развитию асинхронности в Rust идут в не совсем нужном направлении. Даже если вы с ним не согласны, предложенный им способ рассмотрения фич языка программирования довольно полезен.
И продолжения:
Patterns & Abstractions
Const as an auto trait
Forwarded from Блог*
#prog #rust #rustasync #article
Efficient indexing with Quickwit Rust actor framework
Или немного о том, почему разработчики Quickwit решили реализовать свой акторный фреймворк. Также в тексте есть ссылка на статью Actors with Tokio, которая описывает, как создавать свои акторы, имея асинхронный рантайм, и показывает некоторые частые ошибки при подобном наивном подходе.
Efficient indexing with Quickwit Rust actor framework
Или немного о том, почему разработчики Quickwit решили реализовать свой акторный фреймворк. Также в тексте есть ссылка на статью Actors with Tokio, которая описывает, как создавать свои акторы, имея асинхронный рантайм, и показывает некоторые частые ошибки при подобном наивном подходе.
quickwit.io
Efficient indexing with Quickwit Rust actor framework
At Quickwit, we are building the most cost-efficient search engine for logs and traces. Such an engine typically ingests massive amounts of data while serving a comparatively low number of search queries. Under this workload, most of your CPU is spent on…
Forwarded from Блог*
#prog #rust #rustasync #article
Using Rustlang's Async Tokio Runtime for CPU-Bound Tasks
Да, это возможно и в этом есть смысл. Описываемый подход используется в InfluxDB, а InfluxDB используется в проде.
Using Rustlang's Async Tokio Runtime for CPU-Bound Tasks
Да, это возможно и в этом есть смысл. Описываемый подход используется в InfluxDB, а InfluxDB используется в проде.
InfluxData
%%title%% | InfluxData | InfluxData
This blog post argues that the Tokio runtime at the heart of the Rust async ecosystem is a good choice for CPU-heavy jobs.
Forwarded from Блог*
#prog #haskell #article
GADTs
Статья, которая показывает с опорой на лемму Йонеды, что GADT чисто технически не является чем-то, увеличивающим выразительность языка, и что GADT могут быть выражены на обычных ADT (не G) при наличии в языке полиморфизма второго ранга.
GADTs
Статья, которая показывает с опорой на лемму Йонеды, что GADT чисто технически не является чем-то, увеличивающим выразительность языка, и что GADT могут быть выражены на обычных ADT (не G) при наличии в языке полиморфизма второго ранга.
Haskellforall
GADTs
Prelude Some time ago I asked a question on /r/haskell about what unique purpose GADTs served that other language features could not prov...
Forwarded from Блог*
#prog #rust #article
Как известно, в Rust (почти) нет higher-ranked polymorphism. Тем не менее, иногда его можно эмулировать довольно простым образом.
leshow.github.io/post/cheat_rank_n
Как известно, в Rust (почти) нет higher-ranked polymorphism. Тем не менее, иногда его можно эмулировать довольно простым образом.
leshow.github.io/post/cheat_rank_n
Esoterically Typed
Cheating Higher Ranks with Traits
I ran into this a little while ago and thought it would be helpful to share a possible solution.
Imagine you have an enum that describes a set of possible branches, for each branch there is a type …
Imagine you have an enum that describes a set of possible branches, for each branch there is a type …