Jev Course – Prefill-Only Inference & Decision Models from Scratch
freeCodeCamp.org
Summary
Vivek Kalyanarangan demonstrates how to replace slow, token-by-token autoregressive JSON generation with Jev-style prefill-only decision models built from scratch in PyTorch. Stepping through live tensors in a debugger, he contrasts a baseline 130-token autoregressive loop against two single-pass paradigms: an encoder-only BERT approach that mean-pools question spans and scores mask tokens placed before each option, and a decoder-only Qwen 3.6B approach that caches the 38-token context state once and packs multiple isolated questions using a custom 35x73 block-diagonal causal attention mask.
While uncalibrated encoder embeddings require a trained linear head or LoRA adapter to yield accurate probabilities, the decoder implementation achieves 95% and 97% confidence zero-shot by slicing candidate token logits at decision indices. The course concludes by working out Reinforcement Learning for Calibrated Decisions (RLCD), showing how to perturb student logits with random jitters for GRPO advantage calculation and combine cross-entropy with log, spherical, and ordinal Ranked Probability Scores.
How time-sensitive the topic is: Evergreen
By the numbers
130 tokens: Total number of input tokens in the naive JSON fraud-detection prompt fed into the vanilla LLM decoding loop. (Mentioned at 15:27)
152k vocabulary options: Approximate vocabulary size of the Qwen model over which probabilities are computed at each token position. (Mentioned at 16:46)
54 by 768 tensor dimensions: Shape of the last hidden state tensor returned by the encoder model for the 54-token support ticket sequence. (Mentioned at 30:46)
30%: Probability assigned to the 'yes' option by the untrained encoder backbone using a simple dot-product interaction. (Mentioned at 40:09)
5,000 questions: Maximum number of questions Jev supports over a single cached state, pointing to a decoder-based architecture. (Mentioned at 42:00)
28 layers: Number of transformer layers in the Qwen 3.6B model inspected when extracting the KV cache. (Mentioned at 54:40)
35 cross 73 tensor dimensions: Shape of the custom boolean visibility attention mask combining 35 packed question tokens with 38 cached state tokens. (Mentioned at 59:52)
95 percent confidence: Zero-shot probability predicted by the decoder-only Jev implementation that the customer is asking for their money back. (Mentioned at 1:06:54)
97 percent confidence: Zero-shot probability predicted by the decoder-only Jev implementation that the billing team owns the support ticket. (Mentioned at 1:07:27)
400 million parameters: Example encoder model size that Vivek Kalyanarangan says outperforms a comparably sized decoder model thanks to bidirectional attention. (Mentioned at 1:25:06)
Questions this video answers
How does Jev avoid slow token-by-token LLM decoding when generating structured decisions?
Instead of running an autoregressive decode loop that generates JSON keys, quotes, and values one token at a time, Jev formulates the task so the answer is extracted from a single forward prefill pass. This bounds latency to one pass and guarantees predictable probabilities over predefined choice, score, or boolean options.
Vivek Kalyanarangan, 1:12 to 5:30
From this keypoint: Replacing LLM Decoding with One Prefill Pass
Why can't an encoder-only model like BERT cache the document context across multiple questions?
Encoder models use bidirectional attention, meaning every token attends to every other token in the sequence. Whenever a new question is swapped in, the attention weights across the entire context change, forcing the model to recompute the full sequence from scratch for every question.
Vivek Kalyanarangan, 21:23 to 25:23
From this keypoint: Encoder Setup: Question First, Context Last
How do you score multiple-choice options in an encoder-only Jev implementation?
You place the question at the start of the sequence, insert a special `[MASK]` token immediately before each candidate option, and append the context at the end. After one forward pass, you mean-pool the question tokens into a query vector and compute its dot product (or pass through a trained linear head) against the hidden states of the mask tokens.
Vivek Kalyanarangan, 28:15 to 35:00
From this keypoint: Extracting Query and Mask Embeddings in PyTorch
Why does an out-of-the-box encoder model give poor probabilities without fine-tuning?
While pre-trained encoder embeddings capture high-quality semantic signals, their raw hidden states are not trained to produce calibrated probabilities via a simple dot product between question spans and mask tokens. Consequently, an untrained encoder yields only 30% confidence on a clear 'yes' answer and requires fine-tuning a linear head, LoRA adapters, or the backbone.
Vivek Kalyanarangan, 35:01 to 40:41
From this keypoint: Why Out-of-the-Box Encoders Need Fine-Tuning
How do you pack multiple questions into a single decoder forward pass without questions contaminating each other?
In a decoder model, you construct a custom block-diagonal causal attention mask by intersecting a standard lower-triangular causal mask with a question-segment equality matrix, while setting all cached context columns to true. This allows every question to attend to the shared context and its own tokens while completely masking out tokens from earlier or later questions.
Vivek Kalyanarangan, 46:21 to 52:15
From this keypoint: Custom Causal Masking for Multi-Question Packing
What happens in decoder-only first-token scoring when two answer choices start with the same token?
If two options share an initial token (such as 'fraud' and 'fraud review'), a zero-shot decoder that only inspects the first predicted token's logits cannot distinguish between them. You can resolve this collision by renaming the options, mapping choices to single letters (A, B, C, D), or pooling scores across all tokens in the option span.
Vivek Kalyanarangan, 40:41 to 46:21
From this keypoint: Decoder Context Caching and Token Collisions
How does GRPO work in RLCD when a prefill decision model doesn't generate multi-token text rollouts?
Because a prefill decision model outputs a single vector of option logits rather than sampling multiple text sequences, RLCD manufactures synthetic trajectories by adding random perturbations (jitters) to the raw student logits. Each perturbed distribution is scored against a teacher model's probabilities, and the standardized reward advantage guides policy optimization.
Vivek Kalyanarangan, 1:11:12 to 1:16:45
From this keypoint: Distillation and GRPO with Jittered Trajectories
How is the RLCD loss function calculated for calibrating decision probabilities?
The RLCD loss combines standard cross-entropy with a reinforcement learning loss derived from teacher-student distillation. Each trajectory's reward sums a teacher-weighted log score and a normalized spherical score, minus the Ranked Probability Score (RPS) for ordinal questions so predictions closer to the true rank are penalized less.
Vivek Kalyanarangan, 1:16:46 to 1:25:49
From this keypoint: RLCD Loss Maths and Encoder vs. Decoder Trade-Offs
Credible AI™ signals
Confidence: Transparent Code Walkthrough. Vivek Kalyanarangan demonstrates every claim directly in a live debugger using PyTorch tensors, inspecting exact shapes, token IDs, and probability distributions. When discussing proprietary details of Jev or Cloudflare's Clef, he explicitly notes where he is inferring behavior rather than stating established facts.
Bias: Pragmatic Systems Engineering. The instruction favors low-latency, deterministic engineering over open-ended text generation for structured tasks. However, Vivek Kalyanarangan presents balanced architectural trade-offs between encoder and decoder backbones without promoting any commercial product.
Originality (85%): First-Principles Breakdown. Rather than treating decision models as black-box APIs, the course reconstructs prefill-only inference, custom block-diagonal causal attention masks, and GRPO-based RLCD loss calculations from scratch using bare-bones PyTorch.
Depth (92%): Tensor-Level Granularity. The analysis inspects exact tensor dimensions (such as 28 layers, 8 KV heads, and 54x768 hidden states), walks through custom 2D attention mask boolean logic, and works out the mathematical mechanics of log, spherical, and ranked probability scores.
Key points (12)
Short (29 min): key points 1, 4, 7, 8 and 12
Medium (48 min): key points 1, 4, 6, 7, 8, 10, 11 and 12
Relaxed (1h 16min): all 12 key points
1. Replacing LLM Decoding with One Prefill Pass
Timestamp: 00:01:12 to 00:05:30 (4 min)
Speaker: Vivek Kalyanarangan
Standard LLM inference runs a compute-bound prefill pass on the prompt and then loops token by token to decode an answer. Vivek Kalyanarangan explains that Jev skips the autoregressive decode loop entirely, condensing the task into a single forward prefill pass. This design bounds latency and yields predictable, typed outputs across nominal choice, ordinal score, and binary null interfaces.
Impact: High. Why it matters: Eliminating token-by-token generation removes syntax parsing failures and unpredictable latency in production software pipelines that only need structured classifications or scores.
“What Jev attempts to do is it skips the decode part all together and tries to condense the problem statement in the form of one forward pass or one pre-filled statement only.”
In the video: Vivek Kalyanarangan, at 2:26
2. Course Prerequisites and Three-Phase Roadmap
Timestamp: 00:05:30 to 00:07:55 (2 min)
Speaker: Vivek Kalyanarangan
Following this implementation requires familiarity with attention, KV caching, logits, softmax, and PyTorch, though owning a GPU is unnecessary because the coding exercises focus on inference. Vivek outlines a three-phase roadmap covering vanilla token-by-token JSON generation, encoder-only Jev, and decoder-only Jev, followed by theoretical RLCD training and an architectural comparison.
Impact: Low. Why it matters: Setting clear technical prerequisites and keeping code exercises CPU-friendly lets practitioners reproduce the entire inference pipeline on a standard laptop.
“What is not mandatory, however, is you do not need to own a GPU. That's why the coding of this whole course is going to be very inference-heavy.”
In the video: Vivek Kalyanarangan, at 6:41
3. Why Vanilla Autoregressive JSON Decoding Is Slow
Timestamp: 00:12:56 to 00:21:22 (8 min)
Speaker: Vivek Kalyanarangan
Using a pre-trained Qwen model on a credit-card fraud prompt, Vivek Kalyanarangan steps through a standard autoregressive loop generating a Pydantic JSON schema for priority, decision, and escalation. Each iteration processes the 130-token prompt and 152,000-token vocabulary logits just to emit quotes, colons, field names, and values one token at a time. He concludes that this repetitive decoding cycle wastes substantial time when the valid options are already known upfront.
Impact: Medium. Why it matters: Inspecting the step-by-step debugger output makes the inefficiency of generative JSON obvious: most forward passes are spent emitting boilerplate syntax rather than making the actual classification.
“starting from this particular inverted comma to the word priority to then again choosing another token for this particular text and then generating token by token by token took a lot of time”
In the video: Vivek Kalyanarangan, at 20:31
4. Encoder Setup: Question First, Context Last
Timestamp: 00:21:23 to 00:25:23 (4 min)
Speaker: Vivek Kalyanarangan
In an encoder-only architecture like BERT, the input sequence places the question first, injects a special mask token immediately before each candidate option, and appends the context state at the end. Because encoder attention is bidirectional, changing the question alters attention weights across every token position. Consequently, the context cannot be cached and must be re-encoded for every new question.
Impact: High. Why it matters: Bidirectional attention extracts strong representations per parameter, but the inability to cache context makes encoder-only designs expensive when evaluating many questions against a long document.
“every time you actually change the question, you will end up completely changing the attention weights in every position of your attention matrix.”
In the video: Vivek Kalyanarangan, at 24:27
5. Extracting Query and Mask Embeddings in PyTorch
Timestamp: 00:28:15 to 00:35:00 (7 min)
Speaker: Vivek Kalyanarangan
Stepping through `pure_encoding.py` on a 54-token support ticket sequence, Vivek constructs token IDs with a classification token, the question span, mask tokens before the 'no' and 'yes' options, and the context after a separator. A single forward pass returns a 54-by-768 hidden state tensor. He slices and mean-pools the eight question tokens into a single 768-dimensional query vector and extracts the 768-dimensional vectors at the two mask token positions.
Impact: Medium. Why it matters: Mean-pooling the question span and indexing the mask token positions provides a clean, fixed-size geometric representation of both the query and candidate options from a single forward pass.
“Because we're taking all the tokens in the query or the question, and then have averaged out their embeddings to get the best representation of the question itself.”
In the video: Vivek Kalyanarangan, at 33:37
6. Why Out-of-the-Box Encoders Need Fine-Tuning
Timestamp: 00:35:01 to 00:40:41 (6 min)
Speaker: Vivek Kalyanarangan
Taking the dot product between the 2-by-768 option matrix and the 768-by-1 query vector yields two scalars that pass through a softmax to represent option probabilities. However, an untrained encoder backbone outputs only about 30% probability for the correct 'yes' answer on the refund ticket. Because raw embeddings are not naturally aligned to output calibrated probabilities via a dot product, practitioners must train a linear projection head, apply LoRA fine-tuning, or retrain the backbone.
Impact: High. Why it matters: Demonstrating that an untrained encoder fails the zero-shot dot-product test prevents engineers from deploying uncalibrated raw embeddings without at least training a lightweight linear head.
“This is supposed to be a yes, whereas it's only emanating 30%, but mind you, uh the embedding signals are very high-quality. This interaction needs a bit of a getting used to.”
In the video: Vivek Kalyanarangan, at 40:07
7. Decoder Context Caching and Token Collisions
Timestamp: 00:40:41 to 00:46:21 (6 min)
Speaker: Vivek Kalyanarangan
Unlike encoders, decoder-only models use causal masking, allowing the context state to be placed upfront, cached in the KV cache once, and reused across up to 5,000 packed questions. For zero-shot inference, the prompt ends with a colon so the model's next-token logits over the option tokens provide the probabilities directly, while trained variants like Jev use a pointer head and Cloudflare's Clef pools across the option span.
Impact: High. Why it matters: Caching the document state once turns multi-question evaluation from a linear re-encoding bottleneck into a fast lookup, provided option labels avoid first-token collisions.
“Notice that the first token are exactly the same. Now, this is where our simple implementation will go for a toss. Uh it won't know the difference between these two, because the first tokens are literally the same”
In the video: Vivek Kalyanarangan, at 45:12
8. Custom Causal Masking for Multi-Question Packing
Timestamp: 00:46:21 to 00:52:15 (6 min)
Speaker: Vivek Kalyanarangan
When packing multiple questions after a shared context in a single sequence, standard causal masking lets later questions attend to earlier questions. Vivek argues that exposing Question 2 to Question 1 poisons the context and makes answers vary with question order, criticizing Cloudflare's Clef for not masking between questions.
Impact: High. Why it matters: Without masking between packed questions, batching queries into a single forward pass introduces subtle prompt-order bias and breaks reproducibility.
“You're actually poisoning the context with a question you're not even supposed to know or look at. Uh what this will introduce is that if you ask questions in a particular order, you will get different answers.”
In the video: Vivek Kalyanarangan, at 50:09
9. Building the 35x73 Visibility Tensor in PyTorch
Timestamp: 00:52:16 to 01:02:45 (10 min)
Speaker: Vivek Kalyanarangan
In `pure_decoding.py`, Vivek pre-caches a 38-token customer ticket across the 28-layer Qwen model, yielding key and value tensors of shape [1, 8, 38, 128] per layer. He then packs two questions totaling 35 tokens and intersects a lower-triangular causal mask with a segment-equality matrix, prepending 38 columns of ones for the cached state. This produces a 35-by-73 boolean visibility mask that isolates each question while granting both full access to the cached context.
Impact: Medium. Why it matters: Walking through the exact tensor boolean algebra shows how to combine precomputed KV caches with custom 2D attention masks in Hugging Face transformers.
“in the next step itself, the visible should be the concatenation of torch.ones, the width of state length, along with the interaction of the same question and the causal mask that we've constructed.”
In the video: Vivek Kalyanarangan, at 59:07
10. Zero-Shot Decoder Accuracy and Collision Fixes
Timestamp: 01:02:46 to 01:10:36 (8 min)
Speaker: Vivek Kalyanarangan
Passing the 35 question tokens, the 35-by-73 mask, the 38-token KV cache, and offset position IDs into the decoder yields logits in a single forward pass. Extracting logits at decision indices 18 and 34 and normalizing over candidate token IDs produces 95% confidence for 'yes' on the refund question and 97% confidence for 'billing' on team ownership right out of the box.
Impact: High. Why it matters: Unlike the untrained encoder, a pre-trained decoder delivers high zero-shot accuracy immediately when prompted as a next-token completion task with proper position offsets.
“So, we've got, for the first question, 95% confidence that the customer is asking for his money back. So, you see, with the decode only, it works right out the bat.”
In the video: Vivek Kalyanarangan, at 1:06:50
11. Distillation and GRPO with Jittered Trajectories
Timestamp: 01:11:12 to 01:16:45 (6 min)
Speaker: Vivek Kalyanarangan
To calibrate a student model's raw scores [1.0, 0.8, 0.2] (softmax probabilities [0.44, 0.36, 0.19]) toward a teacher model's target distribution [0.7, 0.2, 0.1], RLCD uses teacher-student distillation with Group Relative Policy Optimization (GRPO). Because a prefill decision model outputs fixed option scores rather than sampling diverse text sequences, Vivek explains that multiple trajectories are manufactured by adding random perturbations (jitters) to the student's raw logits.
Impact: High. Why it matters: Injecting random logit jitters adapts GRPO from multi-token text generation to single-step classification heads, enabling reinforcement learning on probability calibration.
“in this case, we don't have multiple trajectories because, again, we've constrained our model to generate certain token probabilities only. So, we'll have to manufacture them out of thin air.”
In the video: Vivek Kalyanarangan, at 1:13:24
12. RLCD Loss Maths and Encoder vs. Decoder Trade-Offs
Timestamp: 01:16:46 to 01:25:49 (9 min)
Speaker: Vivek Kalyanarangan
Each perturbed trajectory's reward combines a teacher-weighted log score with a normalized spherical score, and for ordinal score questions it subtracts the Ranked Probability Score (RPS) to penalize predictions further from the true rank. The final RLCD loss adds standard cross-entropy to this RL loss for backpropagation across a linear head, LoRA adapters, or the full backbone.
Impact: High. Why it matters: Combining proper scoring rules like RPS with a clear architectural decision matrix equips engineers to pick and train the right prefill paradigm for their latency and accuracy constraints.
“So, if the state is to be kept in between questions, the encoder has to reread it every time, but the decoder can read it once and cache it.”
In the video: Vivek Kalyanarangan, at 1:23:39
Key sources
Vivek Kalyanarangan: Course Creator & Author of Quantization and Fast Inference (Manning)
Who's in this
PyTorch
Hugging Face
Jev
BERT
Qwen
Cloudflare
Clef
Also mentioned
Qwen 3.6B (First mentioned at 8:31)
VS Code (First mentioned at 6:08)
Pydantic (First mentioned at 9:11)
GitHub (First mentioned at 1:10:56)
LoRA (First mentioned at 1:23:01)
OpenAI (First mentioned at 9:16)
Gemma (First mentioned at 11:31)
ChatGPT (First mentioned at 19:02)
This analysis was generated by skim (skim.plus), an AI-powered content analysis platform by Credible AI. Scores and classifications represent the platform's AI-generated assessment and should be considered alongside other sources.