Igor Rakov (@IgorRakov) profile picture
Planet Earth
Joined November 2012
Photo by Igor Rakov (@IgorRakov)Photo by Igor Rakov (@IgorRakov)
В 1999 году вышла Quake III Arena. Пока одни разработчики пытались заставить компьютер не сдохнуть от трёх полигонов, ребята из id Software вытворяли с математикой такое, за что в приличном университете могли бы вызвать экзорциста. Игра летала даже на довольно скромном железе. В 2005 году открыли её исходный код, и программисты всего мира полезли выяснять, какой именно договор разработчики подписали с дьяволом. И обнаружили вот это: i = 0x5f3759df - (i >> 1); Причём в оригинальном коде рядом красовался комментарий: // what the fuck? То есть даже исходный код заранее сформулировал реакцию человека, который будет его читать. Эта хреновина вычисляла обратный квадратный корень: 1/√x. Казалось бы, возьми квадратный корень, раздели единицу на результат и не еби людям мозги. Но в те времена процессоры выполняли такие операции относительно медленно. А в трёхмерной графике постоянно требуется нормализовать векторы. Освещение, отражения, геометрия. Таких вычислений может быть огромное количество. И вот вместо того, чтобы честно считать квадратный корень, какой-то математический психопат решил взломать сам принцип хранения чисел в компьютере. Число с плавающей точкой хранится в формате IEEE 754: знак, экспонента и мантисса. Если посмотреть на те же биты как на обычное целое число, внезапно обнаруживается, что полученное значение приблизительно пропорционально двоичному логарифму исходного числа. А обратный квадратный корень в логарифмическом пространстве превращается в умножение на −0,5. То есть вместо сложной математической операции можно сдвинуть биты вправо, вычесть результат из специально подобранной константы и получить довольно приличное приближение. Константа эта: 0x5f3759df Выглядит как пароль от Wi-Fi в психиатрической больнице, но за ней стоит вполне серьёзная математика. Максимальная погрешность первоначального приближения составляет около 3,44%. Многовато? Не вопрос. Прихуячиваем одну итерацию метода Ньютона: y = y * (1.5 - 0.5 * x * y * y); И погрешность падает примерно до 0,175%. Ещё одна итерация, и остаётся около 0,00046%. Всё. Никаких квадратных корней. Никакого деления. Никакого шаманства с покупкой нового процессора. Особенно забавно, что алгоритм появился задолго до Quake III. Его происхождение связывают с Грегом Уолшем и разработками конца 1980-х. А позднее математик Крис Ломонт нашёл чуть более точную магическую константу. Люди буквально занимались научными исследованиями, выясняя, из какого именно шестнадцатеричного числа лучше вычитать половину другого числа, чтобы компьютер перестал тратить время на квадратный корень. Сегодня процессоры имеют специальные аппаратные инструкции для подобных вычислений, поэтому этот трюк во многом утратил практическое преимущество. Но сама инженерная философия прекрасна. Когда компьютер не успевал считать, программисты оптимизировали математику. Когда математика оказалась недостаточно быстрой, они полезли в устройство чисел. Когда и этого оказалось недостаточно, они заставили представление числа в памяти выполнять часть вычислений. А теперь представьте современное совещание по оптимизации программного обеспечения: «Может, оптимизируем алгоритм?» «Нахуя? У пользователей же 32 гигабайта оперативной памяти. Добавьте ещё один фреймворк». Вот и вся разница между двумя эпохами программирования.
114
473
40
4,211
172,639
This is the best video ever made to teach people about what plastic surgery does to you. It's like a proper horror experience.
585
2,227
385
18,409
6,564,424
Igor Rakov retweeted
The legendary fight that was 100% attack and 0% defense
359
2,009
225
23,923
2,412,173
INSANE: Footage shows aftermath of the Atlantic Asphalt tanker crash into the American Heritage river cruiser on the Mississippi River in New Orleans. 129 passengers were on board at the time of the crash. This is horrifying. Pray 🙏🏻
2,405
12,573
1,277
62,207
6,025,675
This is absolutely brilliant, by legendary Australian investor John Hempton, who explains the core financial paradox at the heart of the AI story (and which also, to some extent, may explain the Jensen Huang story). The numbers say that about $7 trillion in AI compute is set to be built by 2030. For the industry to earn that back, given those chips have a roughly 5-year lifespan and cost a lot to run, they need to generate about $2 trillion of AI revenue a year. Hempton says the only way you can get to these sorts of numbers is by selling AI as a productivity tool to businesses, meaning replacing workers. And since, for reasons he explains in the video, no company fires people to save just 10% in costs, the savings have to be about double what businesses pay for the AI: roughly $4 trillion in savings on wages a year. What does firing $4 trillion worth of workers mean concretely? Hempton calculated this equates to roughly 10% of the OECD’s total wage bill of about $40 trillion: one in every ten dollars paid to workers across the OECD’s 38 member countries. Which, naturally, when you suddenly take that much income out of people’s pockets, would trigger a massive global recession. And here's the paradox: in a massive global recession, there's no way businesses will pay $2 trillion a year for AI, so the return disappears anyway. In other words, AI's only possible path to success given the numbers requires destroying the very economy that is supposed to pay for it. HOWEVER - and here's where the Nvidia/Jensen Huang story might come into play (and, to be clear, this is now me speaking and not Hempton given this interview is prior to the whole Nvidia saga) - this all rests on a core assumption: that compute stays super expensive. Which in practice means Nvidia keeping its pricing power, with a 75% gross margin on its chips. Break Nvidia's pricing power, and the $7 trillion bill, the $2 trillion in revenue and the 10% of jobs all shrink with it. This would also put the whole China story in a different light. Maybe it's not so much a "we don't want the Chinese to be competitive with similar chips to us" story as it is a "we don't want Chinese demand to drive up chip prices" one. Or probably both. And, as such, you could actually think about the US export controls not as a national security measure but as a good old subsidy for US AI players (together with a handicap for their Chinese competitors), a way to limit the price of chips. This holds even with China itself blocking Nvidia imports, since Chinese firms simply rent the chips abroad instead, in places like Southeast Asia, which is precisely what this whole Alice Huang/Megaspeed story is about. The main obstacle for all this was, of course... Jensen. Obviously, the guy wanted the exact opposite: as many buyers as possible, Chinese players included, to keep chip prices and Nvidia’s margins sky-high. He was also the one man with the clout to make that happen. All hard to prove, of course, but I can imagine that quite a few corks popped this week in Anthropic's offices: nothing like the news that the man keeping your biggest cost sky-high is out when you're a week away from a $1.2 trillion IPO.
207
1,608
147
6,110
375,223
If AI is not art, then explain this If they ever did this move it would cost billions, and break the box office Well done Jaxon_Flix, legends
325
757
84
5,772
379,637
Igor Rakov retweeted
Блять чуваки, эффект Манделы реально! Я родился в СССР в 1976, я блять флаг СССР видел тысячу раз. Не было сука звезды — никогда ее не видел над серпом и молотом (то есть верхний вариант — то что я видел все детство и юность) Сейчас решил проверить и охуел. Звезда везде (как во втором варианте). Все сука картинки в Гугле с ней… кроме как сменой версии вселенной объяснить это сложно Охуеть!
A new Mandela Effect is rising. Since when does the Soviet flag carry a star above the hammer and sickle? Many of us remember it clearly without one. If you recall the flag without the star… you may be from the old Earth. Shifted into this denser, clown-world timeline. The memory itself is the proof. The body knows. The soul knows. We are not crazy. We are remembering. I miss the old Earth too. Yet we are here now to hold the Light and anchor a higher one. Who else feels this?
888
839
270
9,382
1,065,226