Part 1 · A tour, top to bottom

Building Open Post-Training System

Studying how open-weight and frontier models fail on cultural knowledge in cyber and social-engineering attacks, and teaching them to secure critical infrastructure.

Part 1 covers the JAX foundation, written from scratch with every number derived: Qwen3-0.6B, a tokenizer, a growing KV cache and cached generation.

Why this exists

Where it started

In middle school I was hooked on computer hacking. I wanted to go down to assembly level and see how an exploit can be reversed, and Stuxnet, a zero-day-powered worm, is the example that stayed with me. Now that I have matured, I want to use AI to research exactly this, and to teach models how to secure computer systems.

The question

Frontier models keep expanding their cybersecurity capabilities, and they have shown they can find real, critical vulnerabilities in systems. So how far can open-weight and frontier models be pushed, or tricked, into committing fraud and social-engineering attacks?

The hypothesis

Models lack cultural knowledge, and attackers can exploit that gap to trick them into helping launch cyber and social-engineering attacks. If the hypothesis holds, it becomes one of the biggest questions for RL, agentic research and model security in general.

The system

The Open Post-Training System is how I test it: an Agent Swarm RL infrastructure on JAX and TPUs, built for long-horizon work. It finds loopholes in models and systems, then post-trains models to secure critical infrastructure. It is not only infrastructure. The infrastructure is the instrument for the research.

The people

This also comes from my earlier work in computer security. In my early career I helped save many people from scams and similar attacks. Scammers prey on people’s lack of awareness about technology, and people in India often know this best. If you have ideas around it, I would like to hear them.

In the open

I report on this publicly as I build it. I have only just started, and there is more to be revealed over the next few months.

01

Know every number before writing a line

The first target is Qwen3-0.6B, a decoder-only Transformer. Before touching code I reconstructed it from its config and checkpoint and accounted for parameters, FLOPs and memory per component, then reconciled the total with the model card. The flow is: token ids, embedding, 28 Transformer blocks, final RMSNorm, LM head, vocabulary logits. The LM head reuses the embedding matrix, so it adds no parameters, but it still costs compute.

596,049,920parameters, LM head tied
28layers · hidden 1024
16 / 8query / KV heads
1,136.875MiB of BF16 weights
Embedding 26.1%
Attention 29.6%
SwiGLU MLP 44.3%

Parameter budget. The norms add 65,536 parameters (0.125 MiB), too small to draw.

ComponentParametersBF16 memory
Token embedding (tied LM head)155,582,464296.75 MiB
Q, K, V, O projections176,160,768336 MiB
Gate, up, down projections264,241,152504 MiB
All RMSNorms (incl. QK-Norm)65,5360.125 MiB
Total596,049,9201,136.875 MiB
Where the numbers come from

Notation: V=151,936 is the vocabulary, dmodel=1,024 the hidden size, B the batch, T the sequence length, and BF16 stores 2 bytes per value.

Pembed=Vdmodel=151,936×1,024=155,582,464Each of the 151,936 tokens owns a learned 1,024-dimensional vector.
Membed=2Pembed=311,164,928bytes≈296.75MiB
E=Wembed[ids]:[B,T]→[B,T,1,024]Mact=2BTdmodel=16,384bytesThe lookup is a gather, not a matrix multiply, so it has no matmul FLOPs. The memory figure is for B = 2, T = 4, which is 16 KiB. Parameter memory is fixed, while activation memory grows with batch and sequence length.
PQ=28×2,048×1,024=58,720,256PK=PV=28×1,024×1,024=29,360,128
PO=28×1,024×2,048=58,720,256Pattn=176,160,768
PFFN=3×28×3,072×1,024=264,241,152
Pnorm=28(1,024+1,024+128+128)+1,024=65,536Per layer: input norm, post-attention norm, Q-Norm and K-Norm. One final norm after layer 28.
P=155,582,464+176,160,768+264,241,152+65,536=596,049,920Subtracting the embedding leaves 440,467,456 non-embedding parameters, which matches the 0.44B on the model card.
Flinear=2BTdindoutFbackward≈2FforwardOne multiply-accumulate counts as 2 FLOPs. The backward pass needs dX = dY·W and dW = dYᵀ·X, two matrix multiplies each the size of the forward one.
02

Loading the checkpoint into a JAX pytree

A pytree is a nested structure of dictionaries whose leaves are arrays, so jit, grad and tree_map understand it natively, and the same shape will later carry gradients and optimizer state. The safetensors file is flat, with 28 separate tensors per weight type. I rename them and stack each type along a new leading axis, so one array holds all 28 layers. That layout is what lets jax.lax.scan compile the layer body once instead of unrolling 28 copies.

1 · The checkpoint is a flat dictionary: 310 tensors
model.embed_tokens.weight [151936, 1024] model.layers.0.self_attn.q_proj.weight [2048, 1024] model.layers.1.self_attn.q_proj.weight [2048, 1024] ⋮ 28 copies of every weight type model.layers.27.mlp.down_proj.weight [1024, 3072] model.norm.weight [1024]
↓ rename and stack every weight type
2 · Twenty-eight separate matrices become one array
layer 0[2048, 1024]layer 27new leading axis: 28jnp.stack(layers, axis=0)q_proj → [28, 2048, 1024]one array, all 28 layers
↓ arrange into a nested dictionary
3 · The JAX pytree: 13 leaves (click a node to collapse it)
params
embed_tokens[151936,1024]155,582,464
layersevery leaf has a leading axis of 28
input_layernorm[28,1024]28,672
q_proj[28,2048,1024]58,720,256
k_proj[28,1024,1024]29,360,128
v_proj[28,1024,1024]29,360,128
q_norm[28,128]3,584
k_norm[28,128]3,584
o_proj[28,1024,2048]58,720,256
post_attention_layernorm[28,1024]28,672
gate_proj[28,3072,1024]88,080,384
up_proj[28,3072,1024]88,080,384
down_proj[28,1024,3072]88,080,384
final_norm[1024]1,024
13 leaves · 596,049,920 parameters · 1,136.875 MiB in BF16
layers = {name: jnp.stack([w[f"model.layers.{i}.{ckpt}.weight"] for i in range(28)], axis=0)
          for name, ckpt in LAYER_WEIGHT_NAMES.items()}        # each leaf: [28, ...]
params = {"embed_tokens": w["model.embed_tokens.weight"], "layers": layers, "final_norm": w["model.norm.weight"]}

layer_i = jax.tree_util.tree_map(lambda w: w[i], params["layers"])   # one layer’s weights
∑leavessize=596,049,920=the ledger in chapter 01The pytree doubles as a built-in check: if the leaf sizes do not add up to the ledger, a tensor is missing or mis-shaped.

Two choices matter. The forward pass is wrapped in jax.jit once, with params passed as an argument: if it were captured, JAX would bake roughly 1.2 GB of weights into the compiled program as constants, making compilation slow and heavy. And rope_theta is a fixed number, so it is static. The loader returns model(input_ids, key_cache, value_cache, cache_position), so generation code never touches the weights. The 0.6B checkpoint has no separate lm_head.weight: the logits come from the transposed embedding.

03

A tokenizer, from scratch

No transformers and no tokenizers: just tokenizer.json, tokenizer_config.json and my own implementation, plus regex (Python’s re lacks Unicode classes like \p{L}) and jinja2 for the chat template. Tokenizer boundaries decide loss masks, stop conditions and log-probabilities in post-training, so I want to know exactly what it does. It must be lossless, deterministic, and aligned with the embedding rows the model was trained with.

  1. Split out the 26 added tokenslongest match first, before anything else
  2. NFC normalizeone canonical form per character, ordinary text only
  3. Regex pre-tokenizea leading space stays with the next word; every digit is its own token
  4. Bytes to visible charactersspace becomes Ġ, newline becomes Ċ; 256 base symbols, no unknown token
  5. BPE merges by rankreplay the learned merges, lowest rank first, cache each pre-token
  6. Vocabulary idsa dictionary lookup; a miss is a bug, so it raises
151,669ids the tokenizer can produce
267padding rows in the 151,936 table
26added tokens, 14 special
131,072maximum length in tokens

Ids 0 to 151,642 are ordinary BPE tokens, and 151,643 to 151,668 are added tokens such as <|im_start|> and <think>. The end-of-sequence token is <|im_end|> (151645) and the padding token is <|endoftext|> (151643). There is no beginning-of-sequence token. The last 267 embedding rows exist for hardware-friendly shapes and are never produced, so when sampling they should be masked out.

Decoding walks the pipeline backwards and buffers bytes across consecutive ordinary tokens, so a character split between tokens (an emoji is four bytes) comes out whole. skip_special_tokens drops the 14 special tokens but keeps added tokens such as <think>. One thing to watch: user text containing <|im_end|> becomes the real control token, which is a prompt-injection surface in agent loops.

The chat format is rendered from the Jinja template in the config. With the generation prompt and thinking switched off, one user message becomes:

<|im_start|>user
What is reinforcement learning?<|im_end|>
<|im_start|>assistant
<think>

</think>

For batches, rows are encoded, optionally truncated, and padded with <|endoftext|> to the longest row, with an attention mask (1 for real tokens, 0 for padding). The padding side is a parameter, because batched generation and training usually want different sides.

04

The layer, piece by piece: norms and RoPE

Every layer runs the same operations on its own slice of the pytree. Yellow squares run once, blue squares run in every layer, and the coral square is where the KV cache is written.

  1. Token ids[B,T]
  2. Embedding gather[B,T,1024]
  3. Input RMSNorm[B,T,1024]
  4. Q / K / V projection2048 · 1024 · 1024
  5. Reshape to headsQ [B,T,16,128] · K,V [B,T,8,128]
  6. QK-Norm, per headγ [128]
  7. RoPE on Q and Kpositions = cache_position + arange(T)
  8. Write K/V into the cache[B,C,8,128]
  9. GQA scores + causal mask[B,8,2,T,C]
  10. Softmax (FP32), times V[B,8,2,T,128]
  11. Merge heads, o_proj[B,T,2048] → [B,T,1024]
  12. Residual add[B,T,1024]
  13. Post-attention RMSNorm[B,T,1024]
  14. SwiGLU: SiLU(gate) · up[B,T,3072]
  15. down_proj, residual add[B,T,1024]
  16. Final RMSNorm[B,T,1024]
  17. LM head (embedding transposed)[B,T,151936]
RMSNorm and QK-Norm

RMSNorm normalizes each token’s vector independently. Unlike LayerNorm there is no mean subtraction and no bias, so the only learned parameter is the per-channel scale γ. The mean of squares is computed in FP32, the result is cast back to the input dtype, and only then multiplied by γ.

RMSNorm(x)=γ⊙x1d∑i=1dxi2+ε,ε=10−6
FRMS≈4DBT,D=28(1,024+1,024+2,048+1,024)+1,024=144,384QK-Norm is applied per head: every 128-dimensional query and key head is normalized on its own, and all heads in a layer share one 128-dimensional γ. That is why Q-Norm and K-Norm have only 128 parameters per layer. Forward cost is about 577,536 FLOPs per token, small next to the matrix multiplies. RMSNorm is memory-bandwidth bound, which is why fused kernels exist.
Rotary positional embeddings

RoPE rotates pairs of dimensions in each query and key head. With head size dh=128 there are 64 pairs, and I use the split-half pairing: dimension i is paired with i+64.

ωi=θ−2i/dh,i=0,1,…,63,θ=1,000,000
φp,i=pωip=c+j,j=0,1,…,T−1Positions are absolute: c is cache_position, so the angle does not restart from zero during incremental decoding.
q1′=q1cosφ−q2sinφq2′=q2cosφ+q1sinφThe same equations are applied to K, and V is never rotated. Each pair costs 4 multiplications and 2 additions, which is 6 FLOPs. There are 16·64 + 8·64 = 1,536 pairs per layer, so 6 × 1,536 × 28 = 258,048 FLOPs per token. RoPE has zero learnable parameters.
05

Grouped-query attention, with the math

Qwen3 uses Grouped-Query Attention: 16 query heads share 8 key-value heads, so each KV head serves two query heads. I never copy K or V. The query heads are reshaped into groups, and the single KV head broadcasts across its group inside the matrix multiply.

16 query headsKV0KV1KV2KV3KV4KV5KV6KV78 key-value heads, each shared by 2 queries
g(h)=⌊h/2⌋,[B,T,16,128]→[B,T,8,2,128]→[B,8,2,T,128]Query head h reads KV head g(h). Keys become [B, 8, 1, 128, C], where the singleton axis is what broadcasts across the two query heads.
S=QK⊤dh∈ℝB×8×2×T×CComputed with FP32 accumulation, then masked and soft-maxed in FP32.
Sij=−∞ifj>c+i
Pij=exp(Sij−mi)∑kexp(Sik−mi),mi=maxkSikSubtracting the row maximum keeps the exponentials finite. Query i sits at absolute position c + i, so each query sees itself and everything before it, and every unwritten cache slot stays masked.
O=PV∈ℝB×8×2×T×128→[B,T,2,048]→Y=OWO⊤∈ℝB×T×1,024Heads are merged back to 16 × 128 = 2,048 dimensions, then o_proj returns to the hidden size.
Cost of attention
FQK=2·B·16·T2·128·28=114,688BT2FPV=114,688BT2
Fattn=229,376BT2Fattn,bwd≈458,752BT2These are dense counts: they treat the whole T × T score matrix as computed even though the causal mask makes about half of it unnecessary.
Mscores=16BT2×4=64BT2Mprobs=16BT2×2=32BT2Mattn=96BT2bytesFP32 scores plus BF16 probabilities, when both are materialized. This quadratic term is what flash-attention kernels avoid writing out.
06

SwiGLU, residuals and the LM head

The feed-forward block is a gated MLP called SwiGLU: three matrix multiplies, with SiLU applied to the gate branch only and the two branches multiplied elementwise. Each decoder layer then has two residual connections, and only the branch inputs are normalized; the residual stream itself stays raw.

SiLU(x)=xσ(x),σ(x)=11+e−x
h=SiLU(xWg⊤)⊙(xWu⊤),y=hWd⊤[B,T,1,024]→[B,T,3,072]→[B,T,1,024]
h1=x+Attn(RMSNorm(x)),y=h1+MLP(RMSNorm(h1))
Fgate=Fup=Fdown=2·3,072·1,024·28BT=176,160,768BT
The LM head

After the last block, the final RMSNorm feeds the LM head, which multiplies by the transposed embedding. Weight tying removes duplicate parameters, not the compute.

logits=RMSNorm(h28)Wembed⊤∈ℝB×T×151,936
FLM=2·1,024·151,936BT=311,164,928BT
Mlogits=2·151,936BT=303,872BTbytesDuring decoding only the last position’s logits are needed, which cuts both by a factor of T. Training and RL are the exception: every completion token needs a log-probability. For 8,192 tokens the BF16 logits alone are 2.32 GiB, and double that if upcast to FP32, which is why implementations compute the loss in chunks.
Forward FLOPs ledger, per token
ComponentForward FLOPs (× BT)
Q, K, V, O projections352,321,536
All RMSNorms577,536
RoPE258,048
Gate, up, down projections528,482,304
SiLU and gating258,048
Residual additions57,344
LM head311,164,928
Total, linear in T1,193,119,744
Attention scores and weighted values229,376 × T (so 229,376 BT² overall)
Ffwd≈1,193,119,744BT+229,376BT2T*=1,193,119,744229,376≈5,201Past about 5,200 tokens the attention-score term costs more than everything else in the forward pass combined (dense count).
07

A cache that grows when it needs to

Without a cache, every generated token recomputes the whole sequence. Past tokens’ keys and values never change, so we store them: keys after RoPE, values as they are, shaped [28, B, capacity, 8, 128]. We track capacity (allocated) separately from cache_size (valid), and double the capacity whenever it is full, instead of fixing a maximum length that would be arbitrary and wasteful.

MKV=2·L·nkv·dh·2bytes=2·28·8·128·2=114,688bytes per tokenThat is 112 KiB per token across all layers: 14 MiB at 128 tokens, 224 MiB at 2,048. With 16 KV heads it would be 229,376 bytes, so GQA halves the cache.
after prefill: 6 real tokens, 4 stale pads, capacity 16decode step 1: the new token overwrites slot 6, cache_size becomes 7full: capacity doubles 16 → 32, valid slots copied acrossvalidstale padnew writefree

Cache slots. After prefill only the first n are valid; padding slots are stale and masked, then overwritten one decode step at a time.

Ck=128·2k∑kCk≤2N=O(N)versus∑n=1N−1n=N(N−1)2=O(N2)Doubling copies O(N) elements in total across all expansions, so an insertion costs O(1) amortized. Growing by one slot copies the whole cache every time. Doubling also means a cache that grows to N tokens changes capacity only O(log N) times, and JAX recompiles only on a capacity change.

Because the cache has unused slots, the causal mask is built from absolute positions rather than a lower-triangular T × T matrix. A slot that has not been written yet sits at a position greater than every query, so it is always masked. That is why the model receives the full-capacity buffers and array shapes stay fixed between growth events.

Fno cache(T=64)≈64·1,193,119,744+229,376·642≈76.4+0.94≈77.3GFLOPs
Fcached≈1,193,119,744+229,376C≈1.2GFLOPsRoughly a 64× reduction in forward FLOPs per generated token at 64 positions, and the gap grows with the sequence length.
No cache≈ 77 GFLOPs
With cache≈ 1.2 GFLOPs

Still open: attention runs over the capacity, not the valid length, so masked slots are still computed (up to about twice the necessary score cost); and the functional updates may copy the buffers each step, which buffer donation or a scan-carry design could fix. I will decide from a profile, not from guessing.

08

Prefill once, then decode one token at a time

Every model call is wrapped by the same three steps, and generation has two phases. Prefill runs the prompt through once. Decode feeds one token per step at position cache_size. The prompt is right-padded to a multiple of 64 so the prefill step recompiles only when it crosses a bucket.

npad=64⌈n/64⌉cache_size is set to n, not n_pad. Only the n real tokens count. The pad tokens still write K/V into the slots after the prompt, but those slots are masked, and decode overwrites them one at a time before anything could attend to them. Causal attention also guarantees real tokens never see the pads.
cache.ensure_capacity(T)                                   # double the buffers if needed
logits, k, v = model(ids, cache.key_cache, cache.value_cache, cache.cache_size)
cache.set_cache(k, v, T)                                   # store buffers, advance cache_size
token = int(jnp.argmax(logits[0, n - 1]))                  # prefill: last REAL position; decode: index 0
y1=argmaxvℓn−1,vGreedy decoding reads the logits at the last real prompt position, index n − 1, not at the end of the padded array.

We pass the full-capacity buffers to the model, not the filled-only view, because the layers write into the free slots. We stop on <|im_end|> or <|endoftext|> before appending, so the stop token never reaches the output, and we skip the forward pass after the last token we will emit. Text is streamed by decoding the whole generated list and printing only the new suffix, holding back a trailing � until the rest of a multi-byte character arrives. A worked example with a 100-token prompt:

StepTokens fedcache_positionCapacity checkcache_size after
Prefill128 (100 + 28 pads)00 + 128 ≤ 128100
Decode 11100101 ≤ 128101
Decode 281127128 ≤ 128128
Decode 291128129 > 128, double to 256129

Compilation, by call: prefill compiles once per padded-length bucket, decode compiles once per cache capacity, and cache_position is a runtime value, so it never triggers a recompile on its own.

09

What broke, and how I fixed it

Wiring the cache end to end surfaced six real bugs. Most were silent: JAX happily returns wrong arrays and drops out-of-range writes without an error.

Value cache never updated

What went wrongA typo wrote the value update into the key-cache variable.

FixEach cache is written from its own tensor.

Wrong cache returned

What went wrongThe value tensor was reshaped for the matmul, then returned in place of the cache.

FixA separate attention-only variable; the real cache is returned.

Arguments misaligned

What went wrongThe layer call skipped the cache arguments, so rope_theta landed in a cache slot.

FixPass caches and cache_position end to end through the scan.

Generation resent everything

What went wrongThe loop fed the whole growing sequence every step and added its length to the cache.

FixPrefill once, then one token per step at cache_size.

Empty cache passed in

What went wrongThe filled-only view has zero slots at the start, so there was nowhere to write.

FixPass the full-capacity buffers; the position mask hides unwritten slots.

Loader could not take a cache

What went wrongA partial binding params by keyword collided with positional arguments.

FixA small wrapper over one compiled forward; weights passed as an argument.

Verification plan: compare cached and uncached logits on the same tokens, including across a capacity expansion, and check that greedy generation matches the recompute-everything loop.

10

From a working model to the research

The JAX foundation is in place. The next parts build toward the research in the project title.

  • Rollouts: sandboxed agent environments.
  • Verifiers: rewards you can trust, with failure analysis on long horizons.
  • Training: GRPO on Qwen3-0.6B with MATH-500 evaluation.
  • Kernels: profile the cache path first, then write Pallas flash attention where the bottleneck really is.
  • Agent swarms: JAX/TPU-native agent swarm RL for long-horizon cybersecurity and social-engineering research on culture.

Code on GitHub →   ← Back home