#TSMC honored 35 suppliers at its 2026 Supply Chain Management Forum on 11/17, with ASML, Lam Research, KLA and Tokyo Ohka Kogyo among the firms winning two awards each. 💡More: https://t.co/qNVE0nPCn0 🔗 $TSM $ASML $LRCX $KLAC
Day 20/100 of Inference Engineering
> today we continue with chapter 7 of inference engineering: section 7.2, autoscaling.
> this is a really long section, so i'll split it into two parts to make sure we cover the content properly, here is part 1:
> as the book puts it, the goal of autoscaling is to make sure you always have enough resources to serve incoming requests, keep latency within your service level agreements (slas) and not waste money on idle gpus.
> simple enough, right? not really...
> since this is a hard task, kubernetes to the rescue... it acts like a manager for your model containers, making sure replicas are created and run on machines with the right resources (gpu, memory, etc).
> kubernetes splits the work into two components: the control plane and the worker plane. the control plane handles routing and scaling decisions. the worker plane runs the containers.
> so to be a bit concrete autoscaling is dynamically adjusting how many replicas of a model are running at a given time, the idea is that capacity should match real demand.
> when deciding when to autoscale, there are two main indicators to watch: utilization and traffic.
> utilization looks at gpu memory or compute usage to decide when to scale. the problem is that this can be a lagging indicator. gpu compute usage may only rise once requests start running, and by then more requests may already be waiting in the queue.
> traffic watches how many requests are coming in. it can pick up a spike in demand and start scaling before that spike shows up in gpu usage.
> utilization and traffic can disagree, for example, a few requests with very long contexts can push gpu utilization to 95%, even when traffic is really low... that's why it's best to monitor both together.
> there are many knobs to tune for autoscaling, some key ones are: min replicas, max replicas, autoscaling window, scale down delay, and concurrency target.
> most of these are self-explanatory, but the autoscaling window needs a bit more explanation. it's how far back you look at recent traffic to decide whether to scale up or down.
> to scale based on traffic, you need to know how many requests each instance can handle at once.
> most model inference services use batching to process multiple requests together.
> there are several approaches for batching: static, dynamic, and continuous batching.
> static batching waits until the batch is full to start.
> dynamic batching starts when the batch fills up or a timeout is reached, whichever comes first.
> continuous batching adds new requests as others finish and free up space.
> when it comes to batching, there's a tradeoff between latency and throughput: bigger batches tend to increase throughput, but usually at the cost of higher per-request latency. no free lunch!
> finally, cold start is the time it takes to spin up a new replica of a model.
> ultimately, cold start speed boils down to the following questions... how fast can you get gpus into the cluster?. how fast can you load the container image? how fast can you load the model weights? and how fast can you start your inference engine, including any compilation.
Autoregressive LLMs vs. diffusion LLMs, clearly explained:
(a popular LLM interview question)
Generating 500 tokens doesn't always require 500 sequential decoding steps.
Autoregressive models extend a response one token at a time. Masked diffusion models can predict multiple positions together, then repeat that process to complete the response.
Both can use transformer components such as embeddings, attention, and feed-forward layers. Their attention patterns and training objectives differ.
1) Autoregressive LLMs
In standard autoregressive decoding, each forward pass produces a probability distribution for the next token.
The selected token is appended, and generation continues from that longer sequence.
Causal attention prevents a position from accessing future positions. Earlier token representations therefore stay unchanged as new tokens arrive.
That allows their KV to be cached and reused.
A 500-token response normally requires 500 sequential token-generation steps, although techniques such as speculative decoding can reduce expensive model passes.
2) Diffusion LLMs
In the masked diffusion approach shown below, generation starts with masked output positions alongside the prompt.
A denoising pass predicts candidate tokens for multiple positions using bidirectional context.
With confidence-based sampling, selected predictions are retained while other positions remain masked for subsequent steps.
The model progressively fills the sequence. It doesn't necessarily produce a complete draft and repeatedly rewrite every token.
Some implementations generate block by block rather than processing the entire response together.
Multiple tokens can be finalized per step, allowing fewer steps than output tokens. The step budget affects both speed and quality.
There are some engineering tradeoffs.
Bidirectional attention makes standard autoregressive KV reuse harder. A token's representation can change when surrounding positions are updated, even if that token itself stays fixed.
Caching therefore depends on the architecture and decoding strategy. Block diffusion, for example, can support KV caching across completed blocks.
Fewer steps also don't guarantee lower latency. Each step may process many positions, so total computation and implementation matter.
Bidirectional conditioning also supports filling gaps in text or code.
I covered how KV reuse works in autoregressive decoding in a separate breakdown.
It covers what gets cached during prefill, how the cache grows during decoding, and why it becomes the main memory bottleneck at long context.
Read it below.
Day 317/365 of GPU Programming
Just found out today the vLLM/inferact folks released a collection of megakernels for TPUs back in September which is a really interesting repo to scroll through. Also one fascinating thing about TPUs is how topologies affect kernel implementation (e.g. in this case, a 2×2×4 TPU chip topology)
Birkaç yıl sonra anlayacaksın, hayat aslında güneşlenmekten, sevdiğin yemekleri bol bol yemekten, gitmek istediğin yerlere gitmekten, bir fincan kahve içmekten, parklarda dolaşmaktan ibaret. O kadar büyük anlamlar yok. En yüce işler bile zamanla sıkıcılık doğurur. Bu yüzden, dünyevi değerler ve anlamlar peşinde kaygıyla koşma. Anlık mutlulukların tadını çıkar, anlık acıları kabul et, hayatın kendisinin keyfini sür; bu bile yeter.
Interesting direction for LLM inference: Dory 1.0 is a 4B model that gets more compute by looping through shared layers instead of generating longer reasoning traces.
same weights, variable depth, better performance. worth a read 👀
Link: https://t.co/GbOuAISoWh
🇺🇸 Изучив финансовую отчетность Nvidia, журналисты The Wall Street Journal обнаружили, насколько рискованной была бизнес-стратегия Дженсена Хуанга. За последние несколько лет глава компании выстроил систему, в которой Nvidia сама финансировала спрос на собственную продукцию.
Схема была довольно простой. Nvidia предоставляла многомиллиардные кредитные гарантии небольшим ИИ-компаниям, которые на эти деньги строили дата-центры и закупали ее чипы. Если стартапам не удавалось найти клиентов на свои вычислительные мощности, Nvidia гарантировала их выкуп. Таким образом, в рамках одной коммерческой сделки компания могла одновременно выступать инвестором, гарантом по кредиту, поставщиком оборудования и покупателем вычислительных мощностей. Nvidia фактически сама создавала рынок сбыта для своей продукции, обеспечивая рост выручки и собственной капитализации.
Теперь эта конструкция оказалась под угрозой: крупнейшие технологические компании начали переходить на чипы собственной разработки, снижая свою зависимость от Nvidia. Между тем компания уже взяла на себя контрактные обязательства по закупкам у поставщиков на $279 млрд, а общий объем ее финансовых и контрактных обязательств, включая условные гарантии, превышает $530 млрд.
Иными словами, Хуанг поставил будущее Nvidia в зависимость от непрерывного роста спроса на искусственный интеллект, который компания во многом сама и финансировала. Если этот спрос начнет сокращаться, расплачиваться за агрессивную стратегию бывшего руководителя придется уже его преемникам.
Теперь Nvidia оказалась перед крайне неприятным выбором. Продолжение политики Хуанга грозит дальнейшим ростом финансовых обязательств, значительная часть которых при неблагоприятном развитии событий может превратиться в реальные долги. Отказ же от этой схемы способен спровоцировать цепочку банкротств зависимых от Nvidia ИИ-стартапов, падение спроса на ее чипы и обвал акций самой компании. Причем последствия такого обвала рискуют выйти далеко за пределы Nvidia, потянув за собой весь американский технологический сектор.
Even the simplest weight edit, a deletion, can teach an LLM new skills!
Meet Deletion Tuning (#NeurIPS2026): just zeroing <0.1% of weights matches full fine-tuning's accuracy at scale. It's thousands of times smaller and avoids forgetting, a step toward continual learning. 🧵👇
Inkling 2 Small took a while... but it's more interesting than I initially thought!
Using attention residuals (like Kimi K3), but without the linear-attention hybrid.
Food for discussion for the end-of-the-year architecture trends analysis!
Day 17/100 of Inference Engineering
> today we continue with chapter 6 of inference engineering. section 6.5: image generation models.
> an image generation model can accept either text or a reference image to produce a new image.
> image generation models are usually iterative denoisers, not autoregressive token generators (like llms).
> image models tend to be much smaller than frontier llms, inference for those models is typically constrained by compute, not by bandwidth.
> the reason is because image models kind of "reuse" the same weights to perform lots of calculations (compute) across image features.
> good to keep in mind, image generation model cards usually show really basic inference examples using the diffusers lib.:
pipe = DiffusionPipeline.from_pretrained("model-name")
image = pipe("A cat").images[0]
> those examples are focused in simplicity rather than performance, so chances are there is plenty of room for optimization...
> in case you don't know, a model card is documentation for an ai model. it explains what the model does, how to use it, its limitations, and usually includes a few code examples.
> so... if you're doing high-performance image model inference, use one of these libraries: sglang diffusion, tensorrt or pytorch.
> also, you can further optimize by using more efficient kernels: attention (flash attention 2, 3, 4), norm. functions like rsnorm, gemm, etc.
> the book explains that torch compilation is also really important.
> it can automatically fuse multiple operations into a single kernel, fusssiiioonnn haaa!
> you can also plug in your own optimized kernels when needed.
> also you can compile for the exact gpu you're targeting, for example: if you want to run on a b200, compile on b200.
> finally, the book explains image generation step by step. early steps create the basic outline, while later steps fill in the details.
> normally, each step runs the denoising model twice: once with prompt guidance and once without.
> there's a cool trick... you can turn off prompt guidance in later steps, saving a lot of compute without sacrificing much quality.
Day 315/365 of GPU Programming
Onto lecture 18 which is part 2 of the series on finding efficiency gains in diffusion models. This is almost the end of the course (two more lectures on distributed training and some guest lectures before final projects), so my conclusion is this course has been really helpful and enjoyable. One interesting facet of the course is that lectures often center a around the focus of the research group itself (MIT's Han Lab) with regular throwbacks to "older" research that came out of the lab but I honestly really enjoyed that part as well since it feels like you get a pretty opinionated look into efficient ML research.
عرفت أهمية كل أشكال البيانات أكثر
خصوصاً بعد تعمقي في مجال مستودعات البيانات وذكاء الأعمال , المحللين والمهندسين يستفيدون من أي نوع للبيانات من ضمنها :
1-قواعد بيانات الشركة أو المؤسسة نفسها
2-جداول إكسل الخاصة بالأقسام الداخلية
3-البيانات الورقية والمؤرشفة
4-والبيانات الخارجية
When people think of CUDA threads on a GPU they usually imagine a single dimensional sequence of threads which is wrong!
What if I told you that CUDA threads can actually be organized in multiple dimensions, using x, y, and z axes?
And it doesn't stop at threads. CUDA blocks and grids can also be organized in 1D, 2D, or 3D.
Let's understand how this works and why even we needed this in the first place
In CUDA every thread has three built-in coordinates: (actual cuda notations)
threadIdx.x.
threadIdx.y
threadIdx.z
These identify a thread's position within its block.
For eg: instead of organizing 256 threads in a single row we could arrange them as a 16 × 16 grid.
Both configurations contain 256 threads but the way we index them is different.
Now, blocks work similarly.
Each block has its own coordinates, accessible through blockIdx.x, blockIdx.y, and blockIdx.z.
We also have:
blockDim: Dimensions of a block in threads.
gridDim: Dimensions of the grid in blocks.
For example, we could launch a kernel with:
dim3 threads(16, 16, 1);
dim3 blocks(4, 4, 1);
kernel<<<blocks, threads>>>(); (this executes the kernel with the given configurations)
This creates a 2D grid of 4 × 4 blocks, with each block containing 16 × 16 threads.
That's 4,096 CUDA threads in total.
Now imagine processing a 64 × 64 image.
Instead of manually assigning every thread a pixel number, each thread can calculate its pixel coordinates using:
int x = blockIdx.x * blockDim.x + threadIdx.x;
int y = blockIdx.y * blockDim.y + threadIdx.y;
The same concept extends to 3D indexing, which is useful when working with volumetric data or scientific computing
One important thing to understand is that these dimensions are logical indexing coordinates. Threads aren't physically moving along x, y, or z axes inside the GPU.
They simply provide a convenient way to organize parallel work and map CUDA threads to the shape of the data we're processing.
If you are following my CUDA series tomorrow, I will put up the 2D , 3D and matrix addition code implementations.
Image reference: Jeremiah van Oosten, CUDA Thread Execution Model , 3Dgep
Learn Linux, Docker, Kubernetes, and networking by solving real-world engineering challenges 🛠️
If you've been looking for a fun way to hone/brush off your infrastructure skills, https://t.co/uXYaq2IFNG has got you covered.
Finally recorded a decent demo of the learning format:
Finally wrote a blog post about this! Normal LLM inference isn't deterministic across devices, but this can be fixed.
Floating-point addition isn't associative, (a + b) + c ≠ a + (b + c), and accumulation order changes with the hardware and kernel used, leading to different outputs on the same prompt.
Integer addition is associative, so doing every op in integers (including softmax and norms) gives bit-identical outputs across GPUs and CPUs.
Github repo and post listed in the comments