Better HN
topnewbestaskshowjobs
Log inSign up

raphlinus

14,081 karma · joined Mar 7, 2014 (12y ago) · 1,887 submissions

I do research on fundamental UI technology and 2D graphics, with a focus on Rust and fonts. @raph@mastodon.online
Submissions

comment 3y ago · link · parent

The standard TeX algorithm doesn't penalize the length of the last line, so doesn't solve this. The implementation in Android, based on Minikin[1], applies some penalty to the last line by default, as it's especially unpleasant on mobile. It also has a "balanced" setting[2] which applies the full penalty, as that's often more aesthetically pleasing in UI contexts, though it would not be a good choice for a running text, as it would result in paragraphs of uneven width.

[1]: https://raphlinus.github.io/text/2022/11/08/minikin.html

[2]: https://developer.android.com/reference/android/widget/TextV...

comment 3y ago · link · parent

I wouldn't describe a GPU architecture as VLIW-like, though there is some overlap. To me, the essence of VLIW is extracting instruction level parallelism by specifying lots of different operations in the same instruction word. To this end, the instruction word has to be quite big (128 bits on Itanium) to specify all those operations.

A modern CPU has the same goal of extracting ILP but accomplishes it in a very different way. The instruction stream is short instructions, each of which specifies a simple operation, and these are reassembled using sophisticated dynamic logic into micro-ops, which then get executed in a fairly similar fashion as a VLIW machine - there are a large number of ports (8 is fairly typical these days), each of which performs a separate operation such as arithmetic, load/store, branch, etc.

A GPU has a similar goal of extracting lots of parallelism but does it in a very different way to both VLIW and modern superscalar CPUs. Each instruction operates over a large SIMD vector - 32 is typical, but this varies from 8 (Intel SIMD-8) to 128 (Imagination & optionally Adreno). The instruction specifies many copies of the same operation, so doesn't have to be that big. On RDNA3 for example[1], the basic instruction size is 32 bits, but 64 bits is also common (see section 6.1 for a summary of scalar and 7.1 for a summary of vector encodings).

These instruction sizes are a bit bigger than typical for CPU, for two main reasons. First, there are a lot of registers (256 vector registers), so that needs a lot of bits to encode. Second, it's common to add extra operations such as negation or absolute value in the same operation. But these operations are generally fairly inexpensive modifications on existing data, not completely separate as in VLIW.

In general, execution on a GPU is in-order, so all the reorder buffers and other techniques of superscalar CPUs are not used. Instead of trying to extract as much parallelism as possible from a single thread, a GPU will use that transistor budget to splat more execution units (and thus more threads) on the chip.

[1]: https://developer.amd.com/wp-content/resources/RDNA3_Shader_...

comment 3y ago · link · parent

Very nice story.

Something like this would appeal to me, actually. It reminds me of Nesin Mathematics Village in Turkey. There are also some similarities to Recurse Center, where I did do a 3-month batch in 2017. It also has a library with some rare items, and a good collection of retrocomputing artifacts.

comment 3y ago · link · parent

A lot of the cultural phenomena around Rust can best be explained in religious terms. It's no accident that we are sometimes referred to as the "Rust Evangelism Strike Force," and the word "zealot" is frequently used, of course largely by critics.

There's a deeper level as well. The concept of "memory safety" which is a core principle of Rust has, I believe, a lot in common with religious concepts of purity and cleanliness. Undefined behavior, by contrast, is an undesirable form of uncleanliness, emotionally similar to trayf in Jewish culture or haram in Muslim culture. Rituals include the `#[deny(unsafe_code)]` incantation, or using cargo-deny or similar tools to make sure uncleanliness hasn't crept in through dependencies.

It's not just Rust, although that's a nexus for a lot of tension and conflict around this issue. Tools for avoiding and mitigating unsafety are often given names evoking cleanliness: "Purify" and "sanitizers."

comment 3y ago · link · parent

Going through the comments provides another datapoint for what I have observed as an ironclad law: the first version of any code involving tricky atomics and synchronization is always wrong. Reasoning about these things is hard for human brains.

I strongly recommend using tools when viable. In Rust a particularly easy-to-use and effective one is loom[1]. Alloy is another good tool that scales well but requires investment. In some cases like the Vulkan memory model, Alloy files are available[2].

[1]: https://docs.rs/loom/latest/loom/

[2]: https://github.com/KhronosGroup/Vulkan-MemoryModel

comment 3y ago · link · parent

That is correct, here is a playground link which shows that result: https://play.rust-lang.org/?version=stable&mode=debug&editio...

comment 3y ago · link · parent

I can speak to the UI question, as I'm very invested in it.

It is way too early to standardize any such thing now. There are, give or take, 5 promising UI toolkits, and a dozen others that are best thought of as experimental and may contain interesting ideas. There's a very wide diversity in approaches, and much of that diversity is not accidental but can be traced to different requirements. If you need to deploy an app both on the web and natively, then that pushes you toward adopting at least some web technologies. If you're working on games or game tooling, then the tradeoffs of immediate mode GUI are much more appealing. Another major axis is how much to rely on platform capabilities for stuff like text layout vs rolling your own.

We need to do a lot more exploration of the design space. I believe there is potential to build really compelling UI in Rust. It's entirely possible we end up with fairly different approaches for different use cases, hopefully converging on common infrastructure for things like accessibility.

But if we standardize anything we have now, it risks "the standard library is where modules go to die."

comment 3y ago · link · parent

This one is fun! However, that particular formula is not my favorite, as it doesn't behave nicely when a is small. The art here is deciding what to special case.

The way I approach this[1] is to choose the sign of the ± to be the same as -b to compute the first root x1. Then the second root is c/(a * x1). There are a few other checks in the code for things overflowing, but that basically gives you very accurate answers across the range.

This is explained a bit in a good Math Exchange post[2]. Jim Blinn's "How to solve a quadratic equation" also makes good reading.

Wait til you get to cubics and quartics.

[1]: https://docs.rs/kurbo/latest/src/kurbo/common.rs.html#116-16...

[2]: https://math.stackexchange.com/questions/866331/numerically-...

comment 3y ago · link · parent

Previously: https://news.ycombinator.com/item?id=16312317

My favorite line from the paper is "the popular and elegant X86 architecture". Very subtle humor, I suspect not many people get it.

comment 3y ago · link · parent

I have an exception that proves the rule. I thought about responding to Julia's call, but decided this was too subtle. But here we go...

A central primitive in 2D computational geometry is the orientation problem; in this case deciding whether a point lies to the left or right of a line. In real arithmetic, the classic way to solve it is to set up the line equation (so the value is zero for points on the line), then evaluate that for the given point and test the sign.

The problem is of course that for points very near the line, roundoff error can give the wrong answer, it is in fact an example of cancellation. The problem has an exact answer, and can be solved with rational numbers, or in a related technique detecting when you're in the danger zone and upping the floating point precision just in those cases. (This technique is the basis of Jonathan Shewchuk's thesis).

However, in work I'm doing, I want to take a different approach. If the y coordinate of the point matches the y coordinate of one of the endpoints of the line, then you can tell orientation exactly by comparing the x coordinates. In other cases, either you're far enough away that you know you won't get the wrong answer due to roundoff, or you can subdivide the line at that y coordinate. Then you get an orientation result that is not necessarily exactly correct wrt the original line, but you can count on it being consistent, which is what you really care about.

So the ironic thing is that if you had a lint that said, "exact floating point equality is dangerous, you should use a within-epsilon test instead," it would break the reasoning outlined above, and you could no longer count on the orientations being consistent.

As I said, though, this is a very special case. Almost always, it is better to use a fuzzy test over exact equality, and I can also list times I've been bitten by that (especially in fastmath conditions, which are hard to avoid when you're doing GPU programming).

comment 3y ago · link · parent

Another real world example, and actually quite relevant to the use case of the original article. Tint and naga are both shader compilers, primarily used for compiling WGSL into SPIR-V, MSL, and HLSL so shaders can be used portably. Tint is in C++ and takes 113.6s for a clean compile on M1 Max. Naga, in Rust, is 17s. That includes serde and a bunch of the usual community crates (quote, syn, thiserror, petgraph).

Admittedly Tint is more mature and sophisticated, but both serve the function I need them for.

comment 3y ago · link · parent

Amen brother.

comment 3y ago · link · parent

As with most such things, there is considerable nuance to this question. If you're careful with your dependencies and optimizing for compile time, it can be quite good. For example, a clean release build of makepad studio on M1 Max is 8.81s.

There are also patterns that can really bloat compile time, especially heavy use of procedural macros to autogenerate code. Using serde to serialize big, complex data types can be a big compile time hit. Monomorphization can also be a problem, but fortunately careful use of boxing of dyn traits can help a lot with both code size and compile time (miniserde is an alternative to serde that's more optimized on these dimensions).

There's also continual and ongoing work to improve compile times. So overall I would say it's definitely a factor, but not necessarily a showstopper.

comment 3y ago · link · parent

Game Programming Patterns, by Bob Nystrom.

Foundations of Game Engine Development (4 volumes), by Eric Lengyel.

comment 3y ago · link · parent

Before going to grad school, I was socially quite isolated, partly as a function of being labeled as gifted, partly growing up in a pretty rural area. Going to grad school let me be among a cohort of true peers for the first time in my life. That was incredibly valuable, and the friendships I formed are still meaningful.

I also benefitted from a first-class (UC Berkeley) academic computer science environment. My masters work was on static memory management for ML-family languages, which turned out to be excellent preparation for Rust. The study of algorithm theory has helped me develop parallel GPU algorithms.

Now I work as a researcher and am doing what I love. If I had stayed on the business track, I might be richer in dollars, but not as happy.

comment 3y ago · link · parent

To me, the single biggest opportunity is performance. There's a lot that can be done if you optimize for that: plumb incremental computation through the pipeline from the app logic all the way to the GPU, run your logic in multiple threads, and just generally minimize the work done. I gave a talk[1] which goes into more detail.

Now, I freely admit that many applications don't need that much performance. But I think having a toolkit that is optimized along those lines could be a good basis for doing work on the other things (developer experience) that make a toolkit great.

[1]: https://www.youtube.com/watch?v=zVUTZlNCb8U

comment 3y ago · link · parent

I'd love to see work along these lines, and hope to talk with Cart soon. However, I'm stretched thin as it is, so certainly won't be leading any such integration work. My main goals for 2023 are to get Vello in real usable shape, and there's quite a lot to be done there (the roadmap is in draft and will be published soon, probably today).

comment 3y ago · link · parent

I would say the most likely reason is that 2D graphics is just plain hard. Jasper's classic essay[1] goes into more detail.

That said, I'd really love to see more stuff along the lines of what you describe. I think Vello could render, for example, something that visually looks like Mini Metro or Mini Motorways. I also of course would be a massive fan of using Euler spirals - the only curve that's truly, really simpler is quadratic Béziers, and making those look good in your application would be hard. I'm about to do a lot of Euler spiral math on GPU as part of the stroke rework, which you may find interesting.

Strokes are easier for GPUs than fills, because you don't have to worry about the winding number issues (non-convex paths, paths with holes, etc). There are two recent papers, Polar Stroking[2] and Converting stroked primitives to filled primitives[3].

Also check out Freya Holmér's excellent Shapes library[4] (easily integrated with Unity).

Tesselating curves via shaders is the future (through mesh shaders in particular), and I've got a colleague working on that, but portable infrastructure seems to me just as thorny a problem as compute. I am very biased, but if it were me I'd try to render the 2D stuff with a 2D renderer like Vello.

Best of luck with your project, and I'd be interested in following the progress. Feel free to stop by the Zulip[5] and ask such questions there, as well.

[1]: https://blog.mecheye.net/2019/05/why-is-2d-graphics-is-harde...

[2]: https://arxiv.org/abs/2007.00308

[3]: http://w3.impa.br/~diego/projects/Neh20/

[4]: https://assetstore.unity.com/packages/tools/particles-effect...

[5]: https://xi.zulipchat.com/#narrow/stream/197075-gpu

comment 3y ago · link · parent

Oh yes, and I probably should have mentioned that as well. I've been talking to the developers but haven't checked in lately. I'll take another look, thanks.

comment 3y ago · link · parent

It's possible you ran into problems with large pathtags, fixed by [235], but that hasn't been merged yet. With that and some other tweaks (we still have to manually adjust buffer sizes, but that will soon be dynamic again as well), we are able to render the paris-30k test file, which has ~50k paths and almost a million path segments.

We will also soon be special-casing rectangles. Might be worth rerunning your experiment in a few weeks when all this has landed.

In any case, glad for your interest!

[235]: https://github.com/linebender/vello/pull/235

comment 3y ago · link · parent

Duh, sorry about that.

comment 3y ago · link · parent

These things are hard, and I don't want to discount any of it. But three observations.

First, browser engines do reimplement most of this stuff, though that's been an evolution, it used to be they relied a lot more on platform text layout, for example. And for the stuff that's not completely reinvented (accessibility), they have a put in a lot of work to make cross-platform abstractions. In many cases (interfacing with the compositor comes to mind), browsers are the only viable open source code bases you can read.

Second, to a large extent OS platforms are stagnating. UWP was going to be a big advance over the old WinAPI ways of doing things, but it ended up being a dud. SwiftUI has performance problems for a number of reasons, including the fact they're still using software rendering for a lot of stuff, and their compositor model requires allocating huge amounts of memory for intermediate textures for all their UI elements.

Third, the business structure around platforms requires them to each do things differently, which creates gratuitous incompatibility. You really only need one high quality library to do, say, text layout, rather than having slightly different and slightly incompatible versions on each platform. (And very few places are gratuitous incompatibilities more frustrating than GPU infrastructure)

So for these reasons, I do believe it's worth exploring a new cross-platform GUI toolkit. It is pretty speculative, though; there are lots of ways it could fail.

Game engines are decent at a lot of this stuff, of which of course GPU infrastructure (and graphics rendering in general) is quite good. Most of them could use work in the text department though :)

comment 3y ago · link · parent

Yes, that's the correct link. For those not following closely, it used to be piet-gpu, but we changed the name since it's not based on the Piet API any more, and the new WGSL shaders are basically a rewrite.

comment 3y ago · link · parent

I really enjoyed this. I use a 5700 XT (RDNA 2) as my one of my main development GPUs, and appreciate its particular strengths, and because of this article am quite tempted to get an RDNA 3 card.

A few observations.

First, the astonishingly low latency for LDS (aka workgroup shared memory). Vello uses this fairly extensively (especially in prefix sum / monoid scan operations, plus the stack monoid), so I'd expect performance to be quite sweet on this card. If every card had this, I'm not sure there'd still be a motivation to do subgroups. I also really liked the chart comparing shared memory latency across cards - I already knew that Intel was slow (especially Gen9 and earlier), so it was nice to see quantitative data.

Second, it seems really odd to me that there's chip area for dual-issue ALU, giving over 60 TFLOPS of f32, but the shader compiler only achieves single issue most of the time. I wonder if there are plans to improve performance over time through software updates.

I'd also be really curious whether using Vulkan subgroup size control would help unlock this higher performance. With that feature, the application can query what subgroup sizes are available (32 and 64 here) and explicitly choose one.

I'm really glad this kind of microbenchmarking is being done, we need more of it.

385.

Requiem for piet-gpu-hal(raphlinus.github.io ↗)

66 points · by raphlinus · 3y ago · 13 comments

comment 3y ago · link · parent

I had a nontraditional background, and was labeled as a gifted kid. At your age, my dad and I were trying to get a software company off the ground, based around products I had created. That was a mixed experience - I learned a lot from it, but it was pretty stressful. At age 22 I decided to go to grad school (not having gotten my undergrad degree btw) and that turned out to be the right decision.

I'm not saying what to do, that's your decision. But I do very strongly recommend watching Bryan Cantrill's talk "Coming of Age"[1]. It goes into considerable detail about the different strengths and weaknesses people have at different ages, and how to make the best of that.

[1]: https://www.youtube.com/watch?v=VzdVSMRu16g

comment 3y ago · link · parent

I am curious about doing the same kind of thing for compute shaders. I'm aware of Kompute.cc (which is Vulkan based) but haven't looked at their GEMM kernels, and also of wonnx for WebGPU ([1] is their GEMM code).

I'm also curious whether warp shuffle operations might be useful to reduce some of the shared memory traffic.

[1]: https://github.com/webonnx/wonnx/blob/master/wonnx/templates...

comment 3y ago · link · parent

It's a super good question. I would say two things here.

First, defining the ideal aesthetics is a really hard problem. When you start listing the various properties of curves (basically chapter 2 of my thesis), you find that there are relentless tradeoffs. Case in point: Cem Yuksel's C2 spline (cited elsethread) lists off a bunch of desirable properties, including local support, but then fails to be closed under subdivision. Turns out you can't have both. For the application it was designed for (taking a sequence of points from a hair simulation and defining geometry that can be rendered, preserving the continuity of the specular highlights), it's great, but I wouldn't want to design a font in it.

Another set of tradeoffs: the conclusion of my thesis is that the Euler spiral is the ideal interpolating spline for making smooth curves. So why isn't it more widely used? Two problems: first, you don't always want optimum smoothness, sometimes you want curves with high tension. Second, when you "push" the curve too far, the math doesn't converge to a unique solution, and the curve jumps around, which is really not a great user experience.

[It turns out that these two issues are related: I believe, but haven't yet firmly established, that by increasing the tension when deviation goes up, you can get a unique solution that's also continuous with respect to the input parameters. My prototype is promising but the solver is not 100% robust when pushed hard. It's a difficult problem.]

The second half of this is that Béziers occupy a really sweet spot in this tradeoff space: they're not as smooth as Euler spirals for making interpolating splines, but they're not that far off either. And they can represent high tension, inflection points, and it's easy to draw approximate superellipses, which is an extremely important family of shapes for font design and other tasks. The fact that the math is simple means you can do all the other computational geometry that's needed.

I am on that quest to define a better curve family, but it's pretty far from the top of my priority list right now, so I expect progress to be slow. It's more of a life goal than something I'm actively working on now. The reason this popping up now is that I used a few days during my vacation to revisit it.

comment 3y ago · link · parent

I am. It is relevant to the topic, and I cite it in the (now two year old) outline for the blog post I intend to write on the topic[1].

I'll point out that Yuksel's spline is not closed under subdivision, which is a pretty big flaw. To be fair, the current version of hyperbezier also has that flaw, but I now believe it can be fixed.

[1]: https://github.com/raphlinus/raphlinus.github.io/issues/40

comment 3y ago · link · parent

I spent a couple days around the new year fiddling with my "hyperbezier" idea, which is a project to make a curve family better suited to creative graphics (including font design) than Béziers. I have been interested in this a long time; my thesis was also motivated by this goal. I now have two drafts, neither of which is quite right; they have complementary strengths and weaknesses. In grappling with the difficulty of this project, and other work I've done over the years, I have come to appreciate both the beauty and the downsides of Béziers. I haven't had a chance to write down my latest thoughts, so will hijack this thread.

The greatest strength of a cubic Bézier is it ability to accurately model a huge variety of curve shapes, while still having a parameter space that can be successfully navigated by humans. Higher degree Béziers, as well as other curve families with a bunch of tunable knobs, fail that latter test. I have recently come to the conclusion that the ideal number of parameters for a curve family used for interactive design is 4 (using the counting scheme proposed by my thesis), whether the underlying curve is a Bézier, some form of spiral, or something else. A 4-parameter curve family that is not otherwise broken will have O(n^6) scaling, meaning that a subdivision in half will allow it to fit a more or less arbitrary source curve 64 times more accurately. Subdividing by 3 makes it 729 times more accurate, and 4 gives 4096. Thus, you can draw any curve you can imagine with a very small number of cubic Bézier segments.

A 2 parameter curve family by contrast has only O(n^4) scaling. A quadratic Bézier has other limitations, specifically that it cannot represent an inflection, thus an inflection point must be represented as the join of two convex curves and thus a curvature discontinuity. (Euler spirals are a 2 parameter curve that can represent inflections but have other limitations)

It's not just the scaling, Béziers are also capable of representing varying degrees of tension, a property not shared by Euler spirals and related curves. I use the word "tension" to refer to curves that have regions of high relative curvature, as you would observe in a thin flexible strip (elastica) under tension. A Bézier can represent arbitrarily high tension, all the way up to a cusp of infinite curvature (at which point it becomes a semicubical parabola).

Other strengths include being closed under subdivision and affine transformation.

The math for Béziers is simple in some ways (evaluating the position and derivative are nearly trivial) but tricky in others. Arc length is tractable but not trivial (as explained in the segment of the video starting at 14:14). Offset curves are quite difficult, as is the general problem of curve fitting. Computing intersection between Bézier curves is also hard. However, the beauty and flexibility of the curve family makes the solution to these problems worthwhile.

Now for the criticism. People find Bézier curves hard to learn, and amateurs find it difficult to make smooth curves (particularly shapes like "S" in a font). I have recent mathematical insight that sheds light on both these intuitive observations.

The "lumpiness" stems from the tendency of Béziers to have curvature extrema near but not at the endpoint. Curvature extrema are very perceptually relevant, so not having them at endpoints is a problem. A really good way to quantify this property mathematically is to compute an optimum curve fit to, say, a sine wave[1]. It doesn't subdivide at the peaks and troughs, but rather at points near those curvature extrema.

Another mathematical property that suggests there's something weird going on with the parameter space is the presence of "triplets," sets of three Bézier curves that have very different control points but visually identical shapes. Mathematically, this is captured by the fact that solving for Bézier parameters for given endpoint tangents, area, and x-moment is a quartic equation. (The fourth solution matches these quantities but has a loop so is a very different curve). This in turn implies the likelihood of finding a local minimum, perhaps missing a better global solution - both for automated curve fitting processes and human designers tweaking curves to make them more visually appealing.

In sum, after many years with both Bézier curves and alternatives, I wholeheartedly agree with Freya's conclusion (at 19:13): Bézier curves are sometimes a little messy, but with the simplicity of their construction and the flexibility of their uses, I think they're beautiful, despite their flaws.

[1]: https://xi.zulipchat.com/#narrow/stream/260979-kurbo/topic/F...

1
121314
63